qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
37,447,797
I want to create a process and write some text from my haskell program into the process's stdin periodically (from an IO action). The following works correctly in GHCi but don't work correctly when built and run. In GHCi everything works perfectly and the value from the IO action is fed in periodically. When built and run however, it seems to pause for arbitrarily long periods of time when writing to stdin of the process. I've used `CreateProcess` (from `System.Process`) to create the handle and tried `hPutStrLn` (bufferent set to `NoBuffering` -- `LineBuffering` didnt work either). So I'm trying the `process-streaming` package and `pipes` but can't seem to get anything to work at all. The real question is this: How do i create a process from haskell and write to it periodically? Minimal example that exhibits this behavior: ``` import System.Process import Data.IORef import qualified Data.Text as T -- from the text package import qualified Data.Text.IO as TIO import Control.Concurrent.Timer -- from the timers package import Control.Concurrent.Suspend -- from the suspend package main = do (Just hin, _,_,_) <- createProcess_ "bgProcess" $ (System.Process.proc "grep" ["10"]) { std_in = CreatePipe } ref <- newIORef 0 :: IO (IORef Int) flip repeatedTimer (msDelay 1000) $ do x <- atomicModifyIORef' ref $ \x -> (x + 1, x) hSetBuffering hin NoBuffering TIO.hPutStrLn hin $ T.pack $ show x ``` Any help will be greatly appreciated.
2016/05/25
[ "https://Stackoverflow.com/questions/37447797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2265553/" ]
This is a pipes `Producer` that emits a sequence of numbers with a second delay: ``` {-# language NumDecimals #-} import Control.Concurrent import Pipes import qualified Data.ByteString.Char8 as Bytes periodic :: Producer Bytes.ByteString IO () periodic = go 0 where go n = do d <- liftIO (pure (Bytes.pack (show n ++ "\n"))) -- put your IO action here Pipes.yield d liftIO (threadDelay 1e6) go (succ n) ``` And, using [process-streaming](http://hackage.haskell.org/package/process-streaming-0.9.1.2), we can feed the producer to an external process like this: ``` import System.Process.Streaming main :: IO () main = do executeInteractive (shell "grep 10"){ std_in = CreatePipe } (feedProducer periodic) ``` I used [`executeInteractive`](http://hackage.haskell.org/package/process-streaming-0.9.1.2/docs/System-Process-Streaming.html#v:executeInteractive), which sets `std_in` automatically to `NoBuffering`. Also, if you pipe `std_out` and want to process each match immediately, be sure to pass the `--line-buffered` option to grep (or use the [`stdbuf`](http://linux.die.net/man/1/stdbuf) command) to ensure that matches are immediately available at the output.
9,642,969
I'm trying to translate a PHP class into JavaScript. The only thing I'm having trouble with is getting an item out of an array variable. I've created a simple jsfiddle [here](http://jsfiddle.net/YznSE/7/). I cannot figure out why it won't work. (EDIT: I updated this code to better reflect what I'm doing. Sorry for the previous mistake.) ``` function tattooEightBall() { this.subjects = ['a bear', 'a tiger', 'a sailor']; this.prediction = make_prediction(); var that = this; function array_random_pick(somearray) { //return array[array_rand(array)]; var length = somearray.length; var random = somearray[Math.floor(Math.random()*somearray.length)]; return random; } function make_prediction() { var prediction = array_random_pick(this.subjects); return prediction; } } var test = tattooEightBall(); document.write(test.prediction); ``` ​
2012/03/10
[ "https://Stackoverflow.com/questions/9642969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1141918/" ]
Works fine here, you are simple not calling ``` classname(); ``` After you define the function. **Update** When you make a call to \*make\_prediction\* , *this* will not be in scope. You are right on the money creating a *that* variable, use it on \*make\_prediction\* : ``` var that = this; this.prediction = make_prediction(); function make_prediction() { var prediction = ''; //initialize it prediction = prediction + array_random_pick(that.subjects); return prediction; } ``` You can see a working version here: <http://jsfiddle.net/zKcpC/> This is actually pretty complex and I believe someone with more experience in Javascript may be able to clarify the situation. Edit2: Douglas Crockfords explains it with these words: > > By convention, we make a private that variable. This is used to make > the object available to the private methods. This is a workaround for > an error in the ECMAScript Language Specification which causes this to > be set incorrectly for inner functions. > > > To see the complete article head to: <http://javascript.crockford.com/private.html>
10,687,527
I want create a new JavaScript object based on an existing JavaScript object. Till now my research led me to jQuery extend function. example: ``` var object1 = { name:'same name', age:'1', occupation:'programmer' } var object2 = { name:'same new name' } ``` Now, when I call: ``` $.extend({},object1,object2); ``` it works perfectly, my problem is when I have object member within the object! ``` var object1 = { name:'same name', age:19, occupation:'programmer', parent:{ name:'parent name', age:35 } } var object2 = { name:'same new name', parent:{ age:40 } } ``` Now, when I call ``` $.extend({},object1,object2); ``` object1.parent is: ``` { age:40 } ``` I want it to be: ``` { name:'same new name', age:40 } ``` Is there a way to achieve this?
2012/05/21
[ "https://Stackoverflow.com/questions/10687527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1308134/" ]
use **deep** parameter for jQuer.extend() method, your code should be: ``` $.extend(true,{},object1,object2) ```
15,006,259
In Mongoid 3.0.21, how to get all model's attributes as a plain Ruby `Hash`? Calling either `#attributes` or `#raw_attributes` returns `Moped::BSON::Document`. While it actually extends `Hash`, ~~several hash method does not work as expected. Particularly `#except` returns unmodified `self`, not hash with given keys stripped off~~. **Update**: `Moped::BSON::Document` properly inherits behavior of `Hash`. I was trying to name attributes with symbols, not strings, that's why `#except` didn't work. Shortly: do `except('pictures')`, not `except(:pictures)`.
2013/02/21
[ "https://Stackoverflow.com/questions/15006259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/304175/" ]
``` Hash[e.attributes] ``` where e is your model instance
35,339
I have a two questions related to the torque converter and shifting. * First, is it possible to lock the torque converter on first gear if I press the gas pedal hard? * Second, is shifting while the torque converter locked good for the car's transmission? Thank you!
2016/08/17
[ "https://mechanics.stackexchange.com/questions/35339", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/21706/" ]
The torque converter locks when the engine rpm (impeller/housing speed of converter) and the transmission input shaft (turbine speed of converter) are roughly equal -- thereby improving efficiency for cruising, but also mitigating any torque multiplaction effect of the torque converter. With the TC locked, the engine is effectively directly coupled to the transmission input, and no longer uses a fluid drive. This is controlled by the transmission control module (TCM), and usually is only activatd in top gear, and at steady cruise (low throttle position). In some cases (my '95 Bronco, I think), this can happen in 3rd and 4th gear. In some cases (my '95 Bronco for certain), this can be defeated with a switch, and a light comes on (mislabeled "OVERDRIVE" in my opinion), which is useful when towing heavy loads and some converter "slip" is warranted. Any input from the accelerator decouples the TC friction clutch, and the transmission reverts to a fluid drive scenario with torque multiplication. This also occurs while shifting (if any), as such a shift would be very harsh wihout the fluid damping effect of the TC. So in most vehicles, a downshift to 3rd would uncouple the TC clutch. I'm not aware of vehicles that lock up the TC clutch in lower gears, as this wouldn't make much sense. Lifting the throttle usually commands the transmission into the highest gear (for fuel efficiency) unless your TCM has a "sport" mode or some such that holds it in gear longer.
31,795,704
I'm trying (if it's possible) to make an upload of an image stored on another site (not on computer) via JavaScript (jQuery allowed) with an AJAX request. Lets say that we have the image `http://example.com/a.jpg`. I need to make an AJAX request, submiting this image to `http://test.com/process.php`. * I can't edit the file `process.php` to accept anything than a *valid uploaded file*. * Browser support is not important. Is this even possible ? Because of security issues we canțt dynamicaly populate a file field, so maybe the is another way to send the file without having the user to select the file. I think I should use `FormData`, not sure.
2015/08/03
[ "https://Stackoverflow.com/questions/31795704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422404/" ]
// Recieving File. ``` var url = "http://example.com/a.jpg" var oReq = new XMLHttpRequest(); oReq.onload = function(e) { var blobData = oReq.response; // not responseText // Sending data. var formData = new FormData(); // JavaScript file-like object var blob = new Blob([blobData], { type: "image/jpeg"}); formData.append("webmasterfile", blob); var request = new XMLHttpRequest(); request.open("POST", "http://test.com/process.php"); request.send(formData); } oReq.open("GET", url, true); oReq.responseType = "blob"; oReq.send(); ``` Resources: <https://developer.mozilla.org/en-US/docs/Web/API/FormData/append> <https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects> <https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest>
5,027,853
Have a string like A=B&C=D&E=F, how to remove C=D part and get the string like A=B&E=F?
2011/02/17
[ "https://Stackoverflow.com/questions/5027853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496949/" ]
Either just replace it away: ``` input.Replace("&C=D", ""); ``` or use one of the solutions form your previous question, remove it from the data structure and join it back together. Using my code: ``` var input = "A=B&C=D&E=F"; var output = input .Split(new string[] {"&"}, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.Split('=', 2)) .ToDictionary(d => d[0], d => d[1]); output.Remove("C"); output.Select(kvp => kvp.Key + "=" + kvp.Value) .Aggregate("", (s, t) => s + t + "&").TrimRight("&"); ```
8,875,122
I'm sending a lot of image files via AfNetworking to a Rails server. On edge and sometimes 3G I get this error: Error Domain=NSPOSIXErrorDomain Code=12 "The operation couldn’t be completed. Cannot allocate memory". This is the code I'm using to send the files: <https://gist.github.com/cc5482059ae3023bdf50> Is there a way to fix this? Online some people suggest that a workaround would be to stream the files. I haven't been able to find a tutorial about streaming multiple files using AFNetworking. How can I do this?
2012/01/16
[ "https://Stackoverflow.com/questions/8875122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247707/" ]
How big are the images? And how many are you trying to send? I can't seem to find an easy way to implement an `NSInputStream` using `AFNetworking`, but there's definitely one thing you should try, which is avoiding putting big objects in the autorelease pool. When you are creating big NSData instances insinde a for loop, and those are going to the autorelease pool, all that memory sticks around for as long as the loop lasts. This is one way to optimize it: ``` for (int i=0; i<[self.sImages count]; i++) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSData *imageData = UIImageJPEGRepresentation([self.sImages objectAtIndex:i], 0.7); [formData appendPartWithFileData:imageData name:@"pics[]" fileName:@"avatar.jpg" mimeType:@"image/jpeg"]; pool drain]; } ``` Or, if you're using LLVM3: ``` for (int i=0; i<[self.sImages count]; i++) { @autoreleasepool { NSData *imageData = UIImageJPEGRepresentation([self.sImages objectAtIndex:i], 0.7); [formData appendPartWithFileData:imageData name:@"pics[]" fileName:@"avatar.jpg" mimeType:@"image/jpeg"]; } } ```
33,533,204
I'm working on the save system for a local co-op game I'm working on. The goal of the code is to establish a Serializable Static class that has instances of the four players and the relevant data they need to store for saving in binary. ``` [System.Serializable] public class GameState { //Current is the GameState referenced during play public static GameState current; public Player mage; public Player crusader; public Player gunner; public Player cleric; public int checkPointState; //Global versions of each player character that contains main health, second health, and alive/dead //Also contains the checkpoint that was last activated public GameState() { mage = new Player(); crusader = new Player(); gunner = new Player(); cleric = new Player(); checkPointState = 0; } } ``` The `Player` Class just contains the ints that track player stats and a bool for if they are in the alive state or not. My issue comes when one of my classes in the game scene needs to get data from this static class. When the static class is referenced, it throws the error. ``` void Start () { mageAlive = GameState.current.mage.isAlive; if (mageAlive == true) { mageMainHealth = GameState.current.mage.mainHealth; mageSecondHealth = GameState.current.mage.secondHealth; } else { Destroy(this); } } ``` I am new to coding so I'm not sure how Unity interacts with static classes that don't inherit from `MonoBehaviour`. I based this code off of a tutorial that worked pretty similarly, so I'm not sure what the issue is.
2015/11/04
[ "https://Stackoverflow.com/questions/33533204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5430987/" ]
Nothing is initialising `current`. One quick solution is to initialise `current` like this: ``` public static GameState current = new GameState(); ``` This is the Singleton pattern, you can read a about it all over the web, but [this post](http://csharpindepth.com/Articles/General/Singleton.aspx) by [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet) is a fairly decent place to start. I'd consider making the `GameState` constructor private, and making `current` (aka `Instance` normally) into a property with only a getter: ``` private static GameState current = new GameState(); public static GameState Current { get { return current; } } ``` There are many more ways to do this, especially if multi-threading is a concern, then you should read the Jon Skeet post.
64,147,412
The following code does not work correctly. I am attempting to print to pdf and fit all rows on one page. Any suggestions? ``` For Each sheet1 In ActiveWorkbook.Worksheets With sheet1.PageSetup .Orientation = xlLandscape .Zoom = False .FitToPagesTall = False .FitToPagesWide = 1 End With Next sheet1 worbook1.ExportAsFixedFormat Type:=xlTypePDF, Quality:=xlQualityStandard, IncludeDocProperties:=False, IgnorePrintAreas:=False, OpenAfterPublish:=False ```
2020/10/01
[ "https://Stackoverflow.com/questions/64147412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12921808/" ]
In order to put your worksheet in one printable page you will need to make both FitToPagesTall and FitToPageWide equal to 1. See below for the revised code: ``` For Each sheet1 In ActiveWorkbook.Worksheets With sheet1.PageSetup .Orientation = xlLandscape .Zoom = False .FitToPagesTall = 1 .FitToPagesWide = 1 End With Next sheet1 worbook1.ExportAsFixedFormat Type:=xlTypePDF, Quality:=xlQualityStandard,_ IncludeDocProperties:=False, IgnorePrintAreas:=False, OpenAfterPublish:=False ```
46,953
I have an interest in developing games professionally and have started learning DirectX 11 to that end. I come from a Java background, but with the recent changes introduced with C++11, I've come to like C++ a lot. Coming from Java, I find that the DirectX API reliance on output arguments and a lot of descriptor structs a little disconcerting. I'm trying to build a framework around the API that returns values instead of using output arguments. The framework also rolls descriptors into the class (e.g. DXGI\_SWAP\_CHAIN\_DESC into a SwapChain class) and internally handles the updating that would be required for any changes. I also plan to use exceptions rather than return codes to handle error conditions. Is such a framework viable or it just a Java programmer carrying over his coding style into C++? EDIT: The goals I'm trying to achieve with the framework are that, I want it to rely on returning values, throwing exceptions, handling memory using C++11 and ATL smart pointers. An early iteration of the framework can be found at: <https://github.com/Dolvic/DirectX-Classes>
2013/01/07
[ "https://gamedev.stackexchange.com/questions/46953", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/24890/" ]
> > I'm trying to build a framework around the API that returns values > instead of using output arguments. The framework also rolls > descriptors into the class (e.g. DXGI\_SWAP\_CHAIN\_DESC into a SwapChain > class) and internally handles the updating that would be required for > any changes. I also plan to use exceptions rather than return codes to > handle error conditions. > > > Is such a framework viable or it just a Java programmer carrying over > his coding style into C++? > > > It's certainly viable, and if it makes you more productive in the long run, then it could be a good idea. However I'd advise caution on two points: * It does sound to me like you're suffering a little from the "culture shock" of an unfamiliar API design and rather than trying to understand it and immerse yourself in it, you're trying to *change* it. This isn't necessarily the best approach. * Some aspects of the D3D API are that way due to convention (the COM-style API it uses is not an uncommon API design, even if it seems unusual to you), but some are there for very good reasons. Be aware that you could be introducing some subtle performance issues in your transformations of the API in the name of making it "easier" to use. These performance issues *probably* won't be serious enough to matter, but then again they might be. It's hard to say beforehand. Finally, wrapper-style APIs don't tend to be terribly interesting from a professional experience standpoint (for example, were you to submit the code to me as part of a job application, I'd probably reject you). I would advise instead that you try to create an API that builds upon D3D but itself exposes a higher level of abstraction than D3D does -- in other words, don't create something with a 1:1 mapping of every interface in D3D to your new "improved" API style, but instead combine related interfaces (employing them in their native style to help you learn them) and expose something more useful. Two such examples might be: * Creating a "model" interface that deals with the vertex and index buffers, textures and shader references necessary to manipulate and render a single logical model to the screen. * Creating a "renderer" interface that abstracts away the details of device, context and swap chain set up and management.
81,107
I thought the following was necessary was necessary for outgoing HTTP on a desktop (non-server): ``` iptables -A INPUT -p tcp -m multiport --sports 80,443 -m conntrack --ctstate ESTABLISHED -j ACCEPT iptables -A OUTPUT -p tcp -m multiport --dports 80,443 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT ``` But, it turns out I need these two to make it work. I don't know why: ``` iptables -A INPUT -i lo -j ACCEPT iptables -A OUTPUT -o lo -j ACCEPT ``` I know the last rule allows UDP to the `lo` interface. But, I thought all I needed was `outgoing TCP for NEW/ESTABLISHED connections` + `incoming TCP for ESTABLISHED connections`. It seemed counter-intuitive to me (because I'm still learning).
2013/06/29
[ "https://unix.stackexchange.com/questions/81107", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/42107/" ]
You obviously don't need `lo` for Internet access. But maybe you have a local DNS server (forwarder) running. DNS uses UDP, and web access requires DNS in addition to HTTP. Your rules do not allow (related) ICMP responses BTW. That will probably lead to problems (unless you use lowered values for MSS/MTU). But you don't even allow outgoing ICMP so that path MTU discovery would't even work.
37,715,908
I have a SSAS Cube in SQL 2012 to which I can connect from Excel 2010 without an issue using a windows user credentials. However whenever I restart the server hosting the cube and I try to refresh the pivot in the excel (in a client machine) it throws and an error saying "**An error was encountered in the transport layer**". I am then prompted to re-enter the password for the windows account I am using to connect to the data source. The problem is that if I have couple of pivots open in different sheets in the same excel book per each pivot I am prompted to do this (even if I do a Refresh and not a Refresh All) which is bit of a trouble. Is there a way to fix this or at least to make sure I have to enter the password only once and it will not seek for each and every pivot being refreshed?
2016/06/09
[ "https://Stackoverflow.com/questions/37715908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1519793/" ]
If you are trying to connect to the cube under credentials which are not the credentials you used to log into your laptop, then the proper way of accomplishing this is the following. Create a new connection from scratch. (You can't modify an existing connection.) Do the following: 1. Data tab... From Other Sources... From Analysis Services... 2. Type in a server name, username, and password... click next 3. choose your database and click next 4. Check "Always attempt to use this file to refresh data". And check "Save password in file". Click Yes when the prompt pops up. 5. Click finish. That will save your username and password (in clear text) into the odc file. (Be aware of this for security purposes.) Based upon your description of the symptoms I suspect you didn't have these checkboxes checked when you created the connection. Thus it would continue to prompt for username/password when it needed to reconnect.
431,032
> > **Possible Duplicate:** > > [Windows 7 64-bit is only using 3 GB out of 4 GB](https://superuser.com/questions/394960/windows-7-64-bit-is-only-using-3-gb-out-of-4-gb) > > > My HP HDX 16 laptop has 4GB of ram and runs a 64-bit system. I always go into Dxdiag for some reason and i always see it says 4096 MB of RAM. But today I felt the PC was misbehaving, so i opened it and it said 3128 MB of RAM. Where did that 1 GB go?? When I check the computer properties, it says I'm using a 64-bit system with 4.00GB of RAM, but why does everything else say it has 3?
2012/05/31
[ "https://superuser.com/questions/431032", "https://superuser.com", "https://superuser.com/users/135525/" ]
The most likely reason is due to the video memory set on your BIOS. Probably it is set to dynamic and it auto-adjusted to 1GB due to some video-heavy application that you run. Check on your BIOS settings.
125,634
I am needing help in the configuration process of my Cisco ASA 5510. I have set up 4 Cisco ASA interconnected together via a big LAN. Each Cisco ASA has 3 or 4 LANs attached to them. The IP routing part is taken care of by OSPF. My problem is on another level. A computer connected to one of the LANs attached to an ASA has no problem communicating with the outside world. The outside world being anything "after" the ASA. My problem is that I am completely unable to have them communicate with another LAN connected to the same ASA. To rephrase this, I am unable to send traffic from one interface of a given ASA to another interface of the same ASA. My configuration is the following : ``` ! hostname Fuji ! interface Ethernet0/0 speed 100 duplex full nameif outside security-level 0 ip address 10.0.0.2 255.255.255.0 no shutdown ! interface Ethernet0/1 speed 100 duplex full nameif cs4 no shutdown security-level 100 ip address 10.1.4.1 255.255.255.0 ! interface Ethernet0/2 speed 100 duplex full no shutdown ! interface Ethernet0/2.15 vlan 15 nameif cs5 security-level 100 ip address 10.1.5.1 255.255.255.0 ! interface Ethernet0/2.16 vlan 16 nameif cs6 security-level 100 ip address 10.1.6.1 255.255.255.0 ! interface Management0/0 speed 100 duplex full nameif management security-level 100 ip address 10.6.0.252 255.255.255.0 ! access-list nat_cs4 extended permit ip 10.1.4.0 255.255.255.0 any access-list acl_cs4 extended permit ip 10.1.4.0 255.255.255.0 any access-list nat_cs5 extended permit ip 10.1.5.0 255.255.255.0 any access-list acl_cs5 extended permit ip 10.1.5.0 255.255.255.0 any access-list nat_cs6 extended permit ip 10.1.6.0 255.255.255.0 any access-list acl_cs6 extended permit ip 10.1.6.0 255.255.255.0 any ! access-list nat_outside extended permit ip any any access-list acl_outside extended permit ip any 10.1.4.0 255.255.255.0 access-list acl_outside extended permit ip any 10.1.5.0 255.255.255.0 access-list acl_outside extended permit ip any 10.1.6.0 255.255.255.0 ! nat (outside) 0 access-list nat_outside nat (cs4) 0 access-list nat_cs4 nat (cs5) 0 access-list nat_cs5 nat (cs6) 0 access-list nat_cs6 ! static (outside,cs4) 0.0.0.0 0.0.0.0 netmask 0.0.0.0 static (outside,cs5) 0.0.0.0 0.0.0.0 netmask 0.0.0.0 static (outside,cs6) 0.0.0.0 0.0.0.0 netmask 0.0.0.0 ! static (cs4,outside) 10.1.4.0 10.1.4.0 netmask 255.255.255.0 static (cs4,cs5) 10.1.4.0 10.1.4.0 netmask 255.255.255.0 static (cs4,cs6) 10.1.4.0 10.1.4.0 netmask 255.255.255.0 ! static (cs5,outside) 10.1.5.0 10.1.5.0 netmask 255.255.255.0 static (cs5,cs4) 10.1.5.0 10.1.5.0 netmask 255.255.255.0 static (cs5,cs6) 10.1.5.0 10.1.5.0 netmask 255.255.255.0 ! static (cs6,outside) 10.1.6.0 10.1.6.0 netmask 255.255.255.0 static (cs6,cs4) 10.1.6.0 10.1.6.0 netmask 255.255.255.0 static (cs6,cs5) 10.1.6.0 10.1.6.0 netmask 255.255.255.0 ! access-group acl_outside in interface outside access-group acl_cs4 in interface cs4 access-group acl_cs5 in interface cs5 access-group acl_cs6 in interface cs6 ! router ospf 1 network 10.0.0.0 255.255.255.0 area 1 network 10.1.4.0 255.255.255.0 area 1 network 10.1.5.0 255.255.255.0 area 1 network 10.1.6.0 255.255.255.0 area 1 log-adj-changes ! ``` There is nothing really complicated in this configuration. It just NATs from one interface to another and that's it. I have tried enabling *same-security-traffic permit inter-interface* but that doesn't help. I therefore must be missing something a little bit more complicated. Does anyone know why I cannot foward traffic from one interface to another ? Thank you in advance for your help, Antoine
2010/03/24
[ "https://serverfault.com/questions/125634", "https://serverfault.com", "https://serverfault.com/users/3431/" ]
It is all very well posting theoretical NTFS limits as some other posters have done, however you will find that in reality if you put 100k files in a folder, performance on accessing those files significantly drops. This is the case not just with NTFS but all the popular Linux filesystems as well. The easiest method is to divide them into subfolders holding no more than 10k-20k each. If your naming is relatively evenly distributed you can do this by the first few characters of the filename to keep it simple. You want to create these folders in one go, not on the fly, so that the root folder is not fragmented. There is also the issue of wasted space in blocks if you files are small and do not align to the block size. If this is the case then you may want to look at combining files to match it.
911,721
I need some help with this proposition: If $f:\mathbb{C}\longrightarrow \mathbb{C}$ is an entire function such that $\{z\in \mathbb{C}:f(z)=w\}$ is finite for all $w\in \mathrm{Im} (f)$ then $f$ is a polynomial. Any hint would be appreciated.
2014/08/28
[ "https://math.stackexchange.com/questions/911721", "https://math.stackexchange.com", "https://math.stackexchange.com/users/34276/" ]
Hint: If $f$ is entire then it is a polynomial if and only if it does not have an essential singularity at $\infty$.
12,950,017
I have a Javascript code that opens a pop-up windows which contains a table. The problem is that table contains too many rows to be displayed on the screen area. On IE and Chrome i have a scroll bar to move up and down, but on Firefox i don't. This is the javascript code: ``` function openWindowInsertResp() { ............. dropDownValueA + "&subactivityID=" + dropDownValueS, "PartialTask", "status = 1,height = auto,width = 900,top = 100,left=250,resizable = 1"); ............. } ``` and this is the HTML: ``` <table style="border:none; width:100%;"> <tr> <th style="text-align:center;"> No.</th> <th style="text-align:center;">Description</th></tr> @{ int i=1; foreach (Project.Domain.Entities.Labor_JobDesc cr in contracts) { <tr style="border:none"> <td style="text-align:center; width:2%;">@i</td> <td style="text-align:center;"> <textarea cols="auto"; rows="auto"; style="width:100%;"; readonly="readonly"> @cr.Res</textarea> </td> </tr> i++; } } </table> ``` What I have to do to have a scroll bar on Firefox? Any ideas? Thanks in advance.
2012/10/18
[ "https://Stackoverflow.com/questions/12950017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1472162/" ]
You should use the adjustHeight API in order to do this. Calling the API without any arguments will adjust the iFrames height to fit it's contents. <http://opensocial-resources.googlecode.com/svn/spec/trunk/Core-Gadget.xml#gadgets.window.adjustHeight>
24,613,146
This piece of code is trying to change the colour of the chart bars according to the Quarter (four quarters of a year and the same colour for every other quarter) so my x-axis label is by month and I am trying to search for it and then use the Month() function to get the month number. ``` Sub chartcolour() Dim c As Chart Dim s As Series Dim iPoint As Long Dim nPoint As Long WSChart1.Activate ActiveSheet.ChartObjects("Chart 3").Activate Set c = WSChart1.ChartObjects("Chart 3") Set s = c.SeriesCollection(1) nPoint = ActiveChart.SeriesCollection(1).Points.Count For iPoint = 1 To nPoint If Month(s.XValues(iPoint)) = 11 Or 12 Or 1 Then s.Points(iPoint).Interior.Color = RGB(153, 153, 255) ElseIf Month(s.XValues(iPoint)) = 2 Or 3 Or 4 Then s.Points(iPoint).Interior.Color = RGB(153, 51, 102) ElseIf Month(s.XValues(iPoint)) = 5 Or 6 Or 7 Then s.Points(iPoint).Interior.Color = RGB(153, 153, 255) Else s.Points(iPoint).Interior.Color = RGB(153, 51, 102) End If Next End Sub ```
2014/07/07
[ "https://Stackoverflow.com/questions/24613146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3812787/" ]
For some reason you can't loop through the xvalues property because it's not a collection (you get an Error 451). See the code at the link below on how to work around it with an array variable. [how to loop through xvalues](https://stackoverflow.com/a/33138867/5446655)
16,950
I'm an English speaker learning Russian and from the little bit of French that I know the negation construct "**ne pas**" feels quite similar to "**не раз**". Is there in fact a historical connection between these two negation constructs?
2018/08/08
[ "https://russian.stackexchange.com/questions/16950", "https://russian.stackexchange.com", "https://russian.stackexchange.com/users/10407/" ]
The constructs are not linked etymologically. The French *pas* comes from the Latin word for "step" and the constructs like "ne … pas" originally literally meant "don't (move, walk etc.) a single step", and were only used with the actual verbs of motion. *Pas* has later grammaticalized (become a function word rather than a content word) and is now used with all verbs, not only verbs of motion. The Russian *раз* originally meant "strike" and is cognate to *разить* ("to strike", "to hit"). *За один раз* originally meant "in one strike", then the metaphor had worn out and the word's original meaning had been forgotten. This word is still a content word (meaning "time", "repetition") but has also acquired a grammatical role (*раз ты такой большой, иди работать* // "Now that your are all grown up, go find a job"). Those constructs are indeed similar in the sense that they both started as metaphors ("a single step" in French, "a single strike" in Russian) which later lost their metaphorical meanings and became integral parts of their respective languages. However, there is no historical or etymological connection between them, those are parallel independent developments.
33,498,017
I am trying to copy public key to my multiple hosts in a file called "hostsfile". I am writing a script that will allow me to do that as I am setting a dev environment and I may end up doing it over and over. Googling around I have been able to place insert the public key using ssh-copy-id command and have been able to automate it for one host. However the code needs to be fine tuned to go through each and every host in the hostsfile...unfortunately it completes the first entry and then exits: Below is the code... Appreciate any help in advance.... ``` #!/usr/bin/expect set timeout 10 set f [open "hostsfile"] set hosts [split [read $f] "\n"] close $f set exp_internal 1 foreach host $hosts { spawn ssh-copy-id -i /home/vagrant/.ssh/ansible-use-ssh-key.pub $host expect_after eof { exit 0 } expect "password:" { send "vagrant\r" } expect_after eof { exit 0 } expect "$ " } send "exit\r" expect eof ``` Glen this is what I made out of your comments.... Can you advise please and if you dont mind help with the complete code: ``` #!/usr/bin/expect set timeout 10 set f [open "hostsfile"] close $f set hosts [split [read -nonewline $f] "\n"] foreach host $hosts { spawn ssh-copy-id -i /home/vagrant/.ssh/ansible-use-ssh-key.pub $host expect "password:" send "vagrant\r" expect eof } puts done ``` Hi Glen it worked with the following code as you suggested. However if the key already exists on one of the hosts the process terminates. can you suggest how i can add if/else state for it to not break if the remote host responds with key already exists? Thanks for your help in advance. Below is the code that worked for the first problem. ``` #!/usr/bin/expect set timeout 10 set f [open "hostsfile"] set hosts [split [read -nonewline $f] "\n"] close $f foreach host $hosts { spawn ssh-copy-id -i /home/vagrant/.ssh/ansible-use-ssh-key.pub $host expect "password:" send "vagrant\r" expect eof } ``` puts done
2015/11/03
[ "https://Stackoverflow.com/questions/33498017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5519774/" ]
Use ``` var result = mylist.Cast<object>().Concat(mylist1.Cast<object>()); ``` To unbox it: ``` var list = result.OfType<dealsobj>(); var list1 = result.OfType<itemsobj>(); ```
7,800,905
The scenario goes like this: I have a picture of a paper that I would like to do some OCR. So take the image below as my input example: ![orig_image](https://i.stack.imgur.com/Spl0H.jpg) After successfully detecting the area that corresponds to the paper I'm left with a `vector<Point>` of 4 coordinates that define its location inside the image. Note that these coordinates will probably not correspond to a perfect rectangle due to the distance of the camera and angle when the picture was taken. For viewing purposes I connected the points in the sub-image so you can see what I mean: ![detected_image](https://i.stack.imgur.com/nVd0p.jpg) In this case, the points are: [1215, 43] , [52, 67] , [56, 869] and [1216, 884] At this moment, I need to adjust these points so they become aligned horizontally. What do I mean by that? If you notice the area of the sub-image above, it is a little rotated: the points on right side of the image are positioned a little higher than points on the other side. In other words, we have image **A**, which was exaggerated on purpose to look a little more distorted/rotated than reality, and then image **B** - which is what I would like as the final result of this procedure: A) ![bad_rect](https://i.stack.imgur.com/GJ575.jpg) B) ![ok_rect](https://i.stack.imgur.com/ijOyl.jpg) I'm not sure **which techniques** could be used to achieve this transformation. The application also needs to **detect automatically** how much rotation needs to be done, as I don't have control over the image acquisition procedure. The purpose is to have a new `Mat` with the *normalized* sub-image. I'm not worried about a possible image distortion right now, I'm just looking for a way to identify how much rotation needs to be done on the sub-image and how to apply it and get a more *rectangular area*.
2011/10/17
[ "https://Stackoverflow.com/questions/7800905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/176769/" ]
I think <http://felix.abecassis.me/2011/10/opencv-rotation-deskewing/> and <http://felix.abecassis.me/2011/10/opencv-bounding-box-skew-angle/> will come in handy. The aforementioned posts don't cover perspective warping (only rotation). To get the best results, you'll have to use [`warpPerspective`](http://opencv.willowgarage.com/documentation/cpp/imgproc_geometric_image_transformations.html#warpPerspective) (maybe in conjunction with `getRotationMatrix2D`). Use the angles between line segments to find out how much you need to warp the perspective. THe assumption here is that they should always be 90 degrees and that the closest one to 90 degrees is the "closest" vector as far as the perspective is concerned. Don't forget to normalize your vectors!
64,675,751
While coding a python-based script, i met with a strange html\_table which like: ``` <tr> <td x:str="2020-09-27 18:36:05"></td> <td x:str="SMS"></td> <td x:str="AAA"></td> <td x:str="10658139"></td> </tr> ``` I know I can use MS Excel to convert it to a normal .xls or .xlsx file, but I have too many this kind of files to convert. So I need coding a script to finish the hard job. I have tried to use pandas to handle it, but pandas can not recoginze the data from the file correctly. I guess maybe VBA can handle this problem well, but what I am familiar with is just Python. So can anybody tell me which python library can be used to handle this kind of html-based data table? Any advice would be much appreciated. In fact I have found out an evil way to solve the problem using re. some code like: ``` f=re.sub(r'\sx\:str=\"(.+)\">', r">\1",f) ``` But it looks like too violent.
2020/11/04
[ "https://Stackoverflow.com/questions/64675751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1225091/" ]
Just a guess - you are using the javascript SDK to create the user, not the admin SDK. The Javascript SDK logs the user in after creating the account, so basically you rapidly logged a new account in and out 5 times in a row, hence the mix up with the user ids when creating the firestore documents - it can be that you were just logged out at that moment: > > If the new account was created, the user is signed in automatically. > Have a look at the Next steps section below to get the signed in user > details. > > > [Firebase docs](https://firebase.google.com/docs/auth/web/password-auth#create_a_password-based_account) If you want to bulk-create user accounts you are better off using the admin SDK in a secure environment (e.g. [cloud functions](https://firebase.google.com/docs/functions/callable)) and simply trigger the https function from your frontend. The way you are doing it now means that all the accounts will be created sequentially which can be quite time consuming when you create lots at once - if you are using a cloud function and the admin sdk you can kick off the creation of all accounts in parallel and return a promise once all are finished - something along the lines of: ``` return Promise.all(users.map(user => admin.auth().createUser(user) .then(function(userRecord) { return admin.firestore().collection('users').doc(userRecord.uid).set(...); }) }) ``` [Firebase admin reference](https://firebase.google.com/docs/auth/admin/manage-users#create_a_user)
40,948,094
I am trying to find the **best way to export a complex vector graphic** (i.e., an architectural plan, weighing in at several megabytes uncompressed) for optimal display on the web – and I wonder, if the generally recommended SVG 1.1 option in Illustrator is the best choice. From what I've learned so far, **Scalable Vector Graphics Tiny 1.2 specification**... * used to have **limited viewer support**, but [**not anymore**](https://stackoverflow.com/questions/13236365/optimal-settings-for-exporting-svgs-for-the-web-from-illustrator#comment18061167_13238555). * has [**no effect on file size**](https://stackoverflow.com/a/13238555); best way to reduce it is by shaving off unnecessary decimals with [SVGO](https://jakearchibald.github.io/svgomg/). — I suppose, other than the initial ["baseprofile" parameter](https://www.w3.org/TR/SVGTiny12/struct.html#NewDocument), an SVG Tiny 1.2 file will not structurally differ that much from an identical vector graphic saved as SVG 1.1. * has some [**additional features**](https://stackoverflow.com/a/7850096/1858185) that aren't available in other SVG flavours. * offers a [**simplified DOM**](https://www.w3.org/TR/SVGTiny12/intro.html#SVGTiny12) and **discards some processor-intensive computations** like clipping, masks, symbols, or SVG filter effects. So, regarding the last point, I wonder: Are today's browsers – especially on smartphones – able to **paint an SVG Tiny 1.2 file more efficiently and therefore faster**, knowing that they may allocate fewer processing resources or can omit certain rendering steps?
2016/12/03
[ "https://Stackoverflow.com/questions/40948094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1858185/" ]
``` Select distinct substr(postcode,1,2) from my_table; ```
3,072,304
Here's what I have so far: Since $q$ is continuous and surjective then $X$ is compact. For all $x\in X$ there exists an evenly covered neighborhood $U\_x$, so $\{U\_x \colon x\in X\}$ is an open cover of $X$. So there is a finite subcover $\{ U\_{x\_1},\dots, U\_{x\_n}\}$. For a contradiction, suppose $q$ is not finite-sheeted. Now for for each $x\_i$, we have that $q^{-1}(U\_{x\_i}) = \bigsqcup\_{\alpha \in I\_i} V\_{x\_i,\alpha}$ is disjoint union of open sets of $E$. The sets $\{V\_{x\_1,\alpha}: \alpha \in I\_1\},\dots,\{V\_{x\_n,\alpha}: \alpha \in I\_n\}$ form an open cover of $E$, call it $\mathcal U$. So by compactness have a finite subcover $\mathcal U'\subseteq \mathcal U$. This where I'm having trouble completing the argument. Basically I want to argue that, for say $x\_1$, no finite collection of $\mathcal U$ could cover the fiber $q^{-1}(x\_1)$ since we assumed the fiber is infinite. But I'm having trouble how to show this.
2019/01/13
[ "https://math.stackexchange.com/questions/3072304", "https://math.stackexchange.com", "https://math.stackexchange.com/users/331864/" ]
For convenience, I write $U\_k=U\_{x\_k}$. Without loss of generality, choose the collection $\{U\_1,\ldots,U\_n\}$ such that $n$ is minimal, i.e., no collection of $n-1$ evenly covered open subsets of $X$ covers it. Let $\mathcal U$ be as you have described. I claim that $\mathcal U$ is finite. Otherwise, some $\{V\_{k,\alpha}:\alpha\in I\_k\}$ must be infinite. By compactness of $E$, for some $\alpha\in I\_k$ we have $V\_{k,\alpha}\subset \cup\{V\_{j,\beta}:j\neq k\}$. Applying $q$, we see that $U\_k\subset\cup\{U\_j:j\neq k\}$, contradicting our assumption.
67,388,862
Is this possible to color specific ark between two nodes based on the ark's `<id>` property? if so, how can this be done? Thanks!
2021/05/04
[ "https://Stackoverflow.com/questions/67388862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14832279/" ]
You may use this regex: ```sh ^\d{3}(?:-\d{3})?(?:\s*(?:,|and|or)\s*\d{3}(?:-\d{3})?)*(?=,|$) ``` [RegEx Demo](https://regex101.com/r/NrJWQT/2) **RegEx Details:** * `^`: Start * `\d{3}`: Match 3 digits * `(?:-\d{3})?`: optionally followed by a hyphen and 3 digits * `(?:`: Start non-capture group + `\s*`: Match 0 or more whitespaces + `(?:,|and|or)`: Match a comma or `and` or `or` + `\s*`: Match 0 or more whitespaces + `\d{3}`: Match 3 digits + `(?:-\d{3})?`: optionally followed by a hyphen and 3 digits * `)*`: Start non-capture group. Repeat this group 0 or more times * `(?=,|$)`: Lookahead to assert that we have a comma or End of line ahead of current position
34,324,042
I have this code to make a live connection between my microphone and my speakers. Is it possible to change the pitch of my voice in real time? ``` navigator.getUserMedia( { audio: true }, function(stream) { window.AudioContext = window.AudioContext || window.webkitAudioContext; var ctx= new AudioContext(); // Create an AudioNode from the stream. var mediaStreamSource = ctx.createMediaStreamSource( stream ); // Connect it to the destination to hear yourself (or any other node for processing!) mediaStreamSource.connect( ctx.destination ); }, function(err) { console.log(err); } ); ```
2015/12/16
[ "https://Stackoverflow.com/questions/34324042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2620746/" ]
Actually, this is possible. I did it in the Input Effects demo (<https://webaudiodemos.appspot.com/input/index.html>, select "Pitch Shifter") using a granular resynthesis approach, using a pair of delay nodes with looping ramping delayTimes. If you wanted to do something fancier (like, phase shift vocoding), you'd probably need a ScriptProcessor/AudioWorker.
5,445
The kitchen sink in our home has recently been producing an odd aroma - depending on the day, it's a mix of boiled eggs, sulphur, brackish water, or old food. ### What we have tried * garbage disposal cleaner * clorox * ajax * regular dish soap After any of our attempts so far, the smell returns within 1-2 days - even with no dirty dishes anywhere to be seen. ### What we can't do\* (it's a rental home) * replace the sink * major plumbing What can we do to address this issue? \* if it requires anything "major", it will need a maintenance request, but we're hoping to avoid that and find something simpler
2011/03/30
[ "https://diy.stackexchange.com/questions/5445", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/178/" ]
you could try removing the disposal and p-trap and cleaning those out. also, if your sink has an air gap under it, check to make sure that it's not stuck closed. if it is stuck closed, then when you sink drains, the water that's supposed to be in your p-trap is sucked out and sewer gasses can come up the sink.
61,483,368
I have this line ``` btns = driver.find_elements_by_css_selector('button.css identifier') ``` and it gives a list of matched elements that look like this ``` <selenium.webdriver.remote.webelement.WebElement (session="session hash", element="element hash")> ``` what does the element hash mean and how can I find the html tag with it? I understand selenium is used on multiple languages, but replies in python would be appreciated.
2020/04/28
[ "https://Stackoverflow.com/questions/61483368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11374051/" ]
Add **android:layout\_marginStart** or **android:layout\_marginRight** and **android:layout\_marginEnd** or **android:layout\_marginLeft** to your ImageButtons like this: ``` <ImageButton android:id="@+id/imageButton_1" android:layout_width="0dp" android:layout_height="128dp" android:layout_marginTop="12dp" android:layout_marginStart="10dp" // <==== Change to your margin android:layout_marginEnd="10dp" // <==== Change to your margin /> ``` Your full XML with margins: **(Edited)** ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar_mainActivity" android:layout_width="match_parent" android:layout_height="135dp" android:background="#435cb53f" android:theme="@style/ThemeOverlay.AppCompat.ActionBar" android:layout_alignParentTop="true" android:layout_alignParentStart="true" android:layout_alignParentEnd="true" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:titleTextColor="@android:color/holo_green_light"> <TextView android:id="@+id/textView_ToolBar_FoodSelectionActivity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginEnd="8dp" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:gravity="center" android:layout_gravity="center" android:textColor="@android:color/white" android:textSize="24sp" android:text="Food" /> </android.support.v7.widget.Toolbar> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/bottom_layout" android:layout_below="@+id/toolbar_mainActivity" android:layout_marginTop="0dp" android:layout_marginBottom="0dp" android:layout_alignParentStart="true" android:layout_alignParentEnd="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:fillViewport="true" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <View android:id="@+id/imageButton_1" android:layout_width="0dp" android:layout_height="150dp" android:layout_weight="50" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginBottom="10dp" android:layout_marginTop="10dp" android:background="@drawable/test" /> <View android:id="@+id/imageButton_2" android:layout_width="0dp" android:layout_height="150dp" android:layout_weight="50" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginBottom="10dp" android:layout_marginTop="10dp" android:background="@drawable/test" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <View android:id="@+id/imageButton_3" android:layout_width="0dp" android:layout_height="150dp" android:layout_weight="50" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginBottom="10dp" android:layout_marginTop="10dp" android:background="@drawable/test" /> <View android:id="@+id/imageButton_4" android:layout_width="0dp" android:layout_height="150dp" android:layout_weight="50" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginBottom="10dp" android:layout_marginTop="10dp" android:background="@drawable/test" /> </LinearLayout> </LinearLayout> </ScrollView> <LinearLayout android:id="@+id/bottom_layout" android:layout_width="match_parent" android:layout_height="60dp" android:background="#FFD600" android:layout_alignParentBottom="true" android:layout_alignParentStart="true" android:layout_alignParentEnd="true"> <Button android:id="@+id/button1" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_margin="4dp" android:layout_weight="1" android:background="@drawable/test" android:text="A" /> <Button android:layout_gravity="center_vertical" android:id="@+id/button2" android:layout_weight="1" android:text="B" android:layout_width="0dp" android:layout_margin="4dp" android:layout_height="wrap_content"/> <Button android:layout_gravity="center_vertical" android:id="@+id/button3" android:layout_width="0dp" android:layout_weight="1" android:text="C" android:layout_margin="4dp" android:layout_height="wrap_content"/> <Button android:layout_gravity="center_vertical" android:id="@+id/button4" android:layout_width="0dp" android:layout_weight="1" android:text="D" android:layout_margin="4dp" android:layout_height="wrap_content"/> </LinearLayout> </RelativeLayout> ``` Xml for **@drawable/test** ``` <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="10dp"/> <solid android:color="#ffaa"/> </shape> ``` The problem is solved by replacement ConstraintLayout with RelativeLayout and LinearLayout ------------------------------------------------------------------------------------------
165,713
I saw this question in a book I've been reading: in a group of four mathematicians and five physicians, how many groups of four people can be created if at least two people are mathematicians? The solution is obtained by ${4 \choose 2}{5 \choose 2} + {4 \choose 3}{5 \choose 1} + {4 \choose 4}{5 \choose 0} = 81$. But I thought of the present (wrong) solution: ***Step 1.*** Choose two mathematicians. It gives ${4 \choose 2}$ different ways of choosing. ***Step 2.*** Choose two people from the seven people left. It gives ${7 \choose 2}$ ways of choosing. ***Step 3.*** Multiply. ${4 \choose 2}{7 \choose 2} = 126 = {9 \choose 4}$. It is equivalent of choosing four people in one step. Clearly wrong. I *really* don't know what's wrong in my "solution". It seems like I am counting some cases twice, but I wasn't able to find the error. What am I missing here? PS. It is not homework.
2012/07/02
[ "https://math.stackexchange.com/questions/165713", "https://math.stackexchange.com", "https://math.stackexchange.com/users/17751/" ]
If your group is all four mathematicians, you will count it six times. Each unique pair could be the two you pick first and the other two will be the two you pick second. Similarly, all groups of three mathematicians and one physicist will be counted three times. Since there are 20 groups of 3+1, your overcount is $20\*2+5=45=126-81$
47,097,572
In WooCommerce, I am trying to add an extra add to cart button below product summary. I successfully added an extra button following this code which works for single products: ``` add_action( 'woocommerce_single_product_summary', 'custom_button_after_product_summary', 30 ); function custom_button_after_product_summary() { global $product; echo "<a href='".$product->add_to_cart_url()."'>add to cart</a>"; } ``` But if the product is a variation it doesn't work. please suggest as what to do?
2017/11/03
[ "https://Stackoverflow.com/questions/47097572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4454478/" ]
I have revisited your code a bit, and added a 2nd hooked function for variable products: ``` // For Simple products add_action( 'woocommerce_single_product_summary', 'second_button_after_product_summary', 30 ); function second_button_after_product_summary() { global $product; if( ! $product->is_type( 'variable' ) ) echo '<button type="submit" name="add-to-cart" value="'. esc_attr( $product->get_id() ).'" class="single_add_to_cart_button button alt">'. esc_html( $product->single_add_to_cart_text() ).'</button>'; } // For Variable products add_action( 'woocommerce_single_variation', 'second_button_single_variation', 30 ); function second_button_single_variation() { global $product; echo '<br> <button type="submit" class="single_add_to_cart_button button alt">'. esc_html( $product->single_add_to_cart_text() ).'</button>'; } ``` Code goes in function.php file of your active child theme (or theme) or also in any plugin file. You will get this on variable products: [![enter image description here](https://i.stack.imgur.com/dpKrS.png)](https://i.stack.imgur.com/dpKrS.png)
3,661,836
In Flash, I have a container with several overlapping children. When I give this container an alpha value of .5, some of the children can be seen behind others that overlap them. I would rather be able to take the whole thing as a composite image and blend it that way. Any ideas? cacheAsBitmap on the parent container doesn't have any effect.
2010/09/07
[ "https://Stackoverflow.com/questions/3661836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/187523/" ]
[BlendMode.LAYER](http://www.zedia.net/2008/blendmodelayer-a-must-when-changing-alpha-of-a-displayobject-containing-other-displayobject/)
15,133,545
I am trying to add a counter cache on a a column in a self join association. I have two models User and followings. User has followers and followees, who are from the user table itself. ``` User.rb has_many :followings has_many :followers, :through => :followings has_many :followees, :through => :followings Following.rb class Following < ActiveRecord::Base attr_accessible :followee_id, :follower_id belongs_to :follower, :class_name => "User" belongs_to :followee, :class_name => "User" end ``` now i want to add counter cache on `follower` and `followees`. I have `followers_count` and `followees_count` columns in `user` table. I tried ``` belongs_to :follower, :class_name => "User" , :counter_cache => true ``` But this doesn't return any data in the user table. Any help would be appreciated.
2013/02/28
[ "https://Stackoverflow.com/questions/15133545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2021664/" ]
Try this, ``` belongs_to :follower, foreign_key: 'the_id_of_foreign_key', class_name: 'User', counter_cache: :followers_count ``` You can use the `column_name` instead of `true` in `counter_cache`.
7,075,045
Given input, which shows tag assignments to images, as follows (reading this from php://stdin line by line, as the input can get rather large) ``` image_a tag_lorem image_a tag_ipsum image_a tag_amit image_b tag_sit image_b tag_dolor image_b tag_ipsum ... (there are more lines, may get up to a million) ``` Output of the input is shown as follows. Basically it is the same format with another entry showing whether the image-tag combination exists in input. Note that for every image, it will list all the available tags and show whether the tag is assigned to the image by using 1/0 at the end of each line. ``` image_a tag_sit 0 image_a tag_lorem 1 image_a tag_dolor 0 image_a tag_ipsum 1 image_a tag_amit 1 image_b tag_sit 1 image_b tag_lorem 0 image_b tag_dolor 1 image_b tag_ipsum 1 image_b tag_amit 0 ... (more) ``` I have posted my no-so-efficient solution down there. To give a better picture of input and output, I fed 745 rows (which explains tag assignment of 10 images) into the script via stdin, and I receive 555025 lines after the execution of the script using about 0.4MB of memory. However, it may kill the harddisk faster because of the heavy disk I/O activity (while writing/reading to the temporary column cache file). Is there any other way of doing this? I have another script that can turn the stdin into something like this (not sure if this is useful) ``` image_foo tag_lorem tag_ipsum tag_amit image_bar tag_sit tag_dolor tag_ipsum ``` p/s: order of tag\_\* is not important, but it has to be the same for all rows, i.e. this is not what i want (notice the order of tag\_\* is inconsistent for both tag\_a and tag\_b) ``` image_foo tag_lorem 1 image_foo tag_ipsum 1 image_foo tag_dolor 0 image_foo tag_sit 0 image_foo tag_amit 1 image_bar tag_sit 1 image_bar tag_lorem 0 image_bar tag_dolor 1 image_bar tag_ipsum 1 image_bar tag_amit 0 ``` p/s2: I don't know the range of tag\_\* until i finish reading stdin p/s3: I don't understand why I get down-voted, if clarification is needed I am more than happy to provide them, I am not trying to make fun of something or posting nonsense here. I have re-written the question again to make it sound more like a real problem (?). However, the script really doesn't have to care about what the input really is or whether database is used (well, the data is retrieved from an RDF data store if you MUST know) because I want the script to be usable for other type of data as long as the input is in right format (hence the original version of this question was very general). p/s4: I am trying to avoid using array because I want to avoid out of memory error as much as possible (if 745 lines expaining just 10 images will be expanded into 550k lines, just imagine I have 100, 1000, or even 10000+ images). p/s5: if you have answer in other language feel free to post it here. I have thought of solving this using clojure but still couldn't find a way to do it properly.
2011/08/16
[ "https://Stackoverflow.com/questions/7075045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5742/" ]
Sorry, maby I misunderstood you - this looks too easy: ``` $stdin = fopen('php://stdin', 'r'); $columns_arr=array(); $rows_arr=array(); function set_empty_vals(&$value,$key,$columns_arr) { $value=array_merge($columns_arr,$value); ksort($value); foreach($value AS $val_name => $flag) { echo $key.' '.$val_name.' '.$flag.PHP_EOL; } $value=NULL; } while ($line = fgets($stdin)) { $line=trim($line); list($row,$column)=explode(' ',$line); $row=trim($row); $colum=trim($column); if(!isset($rows_arr[$row])) $rows_arr[$row]=array(); $rows_arr[$row][$column]=1; $columns_arr[$column]=0; } array_walk($rows_arr,'set_empty_vals',$columns_arr); ``` UPD: 1 million lines is easy for php: ``` $columns_arr = array(); $rows_arr = array(); function set_null_arr(&$value, $key, $columns_arr) { $value = array_merge($columns_arr, $value); ksort($value); foreach($value AS $val_name => $flag) { //echo $key.' '.$val_name.' '.$flag.PHP_EOL; } $value=NULL; } for ($i = 0; $i < 100000; $i++) { for ($j = 0; $j < 10; $j++) { $row='row_foo'.$i; $column='column_ipsum'.$j; if (!isset($rows_arr[$row])) $rows_arr[$row] = array(); $rows_arr[$row][$column] = 1; $columns_arr[$column] = 0; } } array_walk($rows_arr, 'set_null_arr', $columns_arr); echo memory_get_peak_usage(); ``` 147Mb for me. Last UPD - this is how I see low memory usage(but rather fast) script: ``` //Approximate stdin buffer size, 1Mb should be good define('MY_STDIN_READ_BUFF_LEN', 1048576); //Approximate tmpfile buffer size, 1Mb should be good define('MY_TMPFILE_READ_BUFF_LEN', 1048576); //Custom stdin line delimiter(\r\n, \n, \r etc.) define('MY_STDIN_LINE_DELIM', PHP_EOL); //Custom stmfile line delimiter - chose smallset possible define('MY_TMPFILE_LINE_DELIM', "\n"); //Custom stmfile line delimiter - chose smallset possible define('MY_OUTPUT_LINE_DELIM', "\n"); function my_output_arr($field_name,$columns_data) { ksort($columns_data); foreach($columns_data AS $column_name => $column_flag) { echo $field_name.' '.$column_name.' '.$column_flag.MY_OUTPUT_LINE_DELIM; } } $tmpfile=tmpfile() OR die('Can\'t create/open temporary file!'); $buffer_len = 0; $buffer=''; //I don't think there is a point to save columns array in file - //it should be small enough to hold in memory. $columns_array=array(); //Open stdin for reading $stdin = fopen('php://stdin', 'r') OR die('Failed to open stdin!'); //Main stdin reading and tmp file writing loop //Using fread + explode + big buffer showed great performance boost //in comparison with fgets(); while ($read_buffer = fread($stdin, MY_STDIN_READ_BUFF_LEN)) { $lines_arr=explode(MY_STDIN_LINE_DELIM,$buffer.$read_buffer); $read_buffer=''; $lines_arr_size=count($lines_arr)-1; $buffer=$lines_arr[$lines_arr_size]; for($i=0;$i<$lines_arr_size;$i++) { $line=trim($lines_arr[$i]); //There must be a space in each line - we break in it if(!strpos($line,' ')) continue; list($row,$column)=explode(' ',$line,2); $columns_array[$column]=0; //Save line in temporary file fwrite($tmpfile,$row.' '.$column.MY_TMPFILE_LINE_DELIM); } } fseek($tmpfile,0); $cur_row=NULL; $row_data=array(); while ($read_buffer = fread($tmpfile, MY_TMPFILE_READ_BUFF_LEN)) { $lines_arr=explode(MY_TMPFILE_LINE_DELIM,$buffer.$read_buffer); $read_buffer=''; $lines_arr_size=count($lines_arr)-1; $buffer=$lines_arr[$lines_arr_size]; for($i=0;$i<$lines_arr_size;$i++) { list($row,$column)=explode(' ',$lines_arr[$i],2); if($row!==$cur_row) { //Output array if($cur_row!==NULL) my_output_arr($cur_row,array_merge($columns_array,$row_data)); $cur_row=$row; $row_data=array(); } $row_data[$column]=1; } } if(count($row_data)&&$cur_row!==NULL) { my_output_arr($cur_row,array_merge($columns_array,$row_data)); } ```
49,313,923
``` select table_name, to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from '||owner||'.'||table_name)),'/ROWSET/ROW/C')) as count from all_tables ``` I would like to get those with one record in the table.
2018/03/16
[ "https://Stackoverflow.com/questions/49313923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9501235/" ]
The query crashes only when the filter predicate is applied. It's probably a bug in some query rewrite optimization. If you wrap the query in a block with the `materialize` hint, it seems to bypass this behavior. ``` with workaround as( select /*+ materialize */ owner ,table_name ,to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from ' || owner || '.' || table_name || ' where rownum <= 2')),'/ROWSET/ROW/C')) as row_count from all_tables where owner = '<your-schema>' ) select owner, table_name, row_count from workaround where row_count = 1; ``` I also found some potential to improve the performance of this query. If you only want tables with exactly one record, there is really no need to count every single record in the table. If you add the predicate `rownum <= 2` Oracle will stop scanning as soon as it has found two records. So the count will be either: * 0, meaning empty table * 1, meaning exactly one record * 2, meaning more than 1 record Edit to show how the optimization work: ``` -- Creating tables create table t0(c number); create table t1(c number); create table t2(c number); create table t3(c number); insert into t1 values(1); insert into t2 values(1); insert into t2 values(2); insert into t3 values(1); insert into t3 values(2); insert into t3 values(3); commit; ``` SQL: ``` /* || Without rownum you can filter on any rowcount you want */ select * from (select 'T0' as t, count(*) as row_count from t0 union all select 'T1' as t, count(*) as row_count from t1 union all select 'T2' as t, count(*) as row_count from t2 union all select 'T3' as t, count(*) as row_count from t3 ) where row_count = 1 -- Return tables having exactly 1 record. ; /* || With rownum <= 1 Oracle will stop counting after it found one row. || So the rowcount will be either 0 or 1. || row_count = 0 means that the table is empty || row_count = 1 means that the table is NOT empty. || || The Rownum predicate prevents us from knowing if there are 2,3,4 or 5 million records. */ select * from (select 'T0' as t, count(*) as row_count from t0 where rownum <= 1 union all select 'T1' as t, count(*) as row_count from t1 where rownum <= 1 union all select 'T2' as t, count(*) as row_count from t2 where rownum <= 1 union all select 'T3' as t, count(*) as row_count from t3 where rownum <= 1 ) where row_count = 1 -- Return tables having at least one record ; /* || With rownum <= 2 Oracle will stop counting after it found two rows. || So the rowcount will be either 0, 1 or 2. || row_count = 0 means that the table is empty || row_count = 1 means that the table has exactly 1 record || row_count = 2 means that the table has more than 1 record || || The Rownum predicate prevents us from knowing if there are exactly two records, or 3,4,5 etcetera */ select * from (select 'T0' as t, count(*) as row_count from t0 where rownum <= 2 union all select 'T1' as t, count(*) as row_count from t1 where rownum <= 2 union all select 'T2' as t, count(*) as row_count from t2 where rownum <= 2 union all select 'T3' as t, count(*) as row_count from t3 where rownum <= 2 ) where row_count = 1 -- Return tables having exactly one record ; ```
70,358,629
I have a string like this: > > This is a sentence.\n This is sentence 2.\n\n\n\n\n\n This is sentence 3.\n\n And here is the final sentence. > > > What I want to is: > > This is a sentence.\n This is sentence 2.\n This is sentence 3.\n And here is the final sentence. > > > I want to remove all duplicated \n characters from a string but keep only one left, is it possible to do like that in javascript ?
2021/12/15
[ "https://Stackoverflow.com/questions/70358629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16604302/" ]
If you truly want to embed `B.dll` *inside* of `A.dll`, you can define `B.dll` as a *resource* of `A.dll` via an [`.rc` script](https://learn.microsoft.com/en-us/cpp/windows/resource-files-visual-studio) in `A.dll`'s project. Then you can use `B.dll` at runtime by first using `(Find|Load|Lock)Resource()` to access the bytes for `B.dll`'s resource and writing them to a tempory file using `(Create|Write)File()` before then loading that file with `LoadLibrary()`.
73,163,221
I'm trying to filter and later access to the child data of a nested json file using PHP but for now i'm unable to do it. Json example: ``` { "_embedded": { "items": [ { "uuid": "zL7j58B5fC3", "dns_records": [ { "type": "TXT", "name": "_amazonses1.test.com" }, { "type": "TXT", "name": "_ddplatform1.test.com" } ] }, { "uuid": "Zf6Yr2n07", "dns_records": [ { "type": "TXT", "name": "_amazonses2.test.com", }, { "type": "TXT", "name": "_ddplatform2.test.com" } ], } ] } } ``` I've tried with this code: ``` $data = json_decode($resp, true); if( ! empty( $data ) ) { foreach($data['_embedded']['items'] as $item){ if($item['uuid'] == $domain_id){ $dns_entries=$item['uuid']['dns_records']['name']; } else { $dns_entries = ''; } echo $dns_entries; } ``` So $domain\_id is an external value that I passed through the function. The idea is that if it matches one of the child's values, then I can extract the values inside that child. If I pass $domain\_id as Zf6Yr2n07 then I need to extract the TXT information (name) inside that child node. e.g. \_amazonses2.test.com Any tip will be highly appreciated.
2022/07/29
[ "https://Stackoverflow.com/questions/73163221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2965052/" ]
First, your JSON is invalid. Make sure to remove trailing commas. Second, you're accessing `$item["uuid"]["dns_records"]["name"]`, but 1. `dns_records` is an array 2. `dns_records` exists on `$item`, not `$item["uuid"]` To get only the first name, just select the first element inside the `dns_records` array: `$item["dns_records"][0]["name"]` Another option is to return an array with all the available names by looping through all child elements of `dns_records` and pushing the `name` to a new array: ```php if( ! empty( $data ) ) { $dns_entries = []; foreach($data['_embedded']['items'] as $item){ if($item['uuid'] == $domain_id){ foreach($item['dns_records'] as $dns_item) { $dns_entries[] = $dns_item["name"]; } } } print_r($dns_entries); // print_r because echo doesn't work with arrays } ``` [Live demo on onlinephp.io](https://onlinephp.io/c/098ae)
2,581,650
> > Let $a$ be an integer. Prove that there are infinitely many integers $b$ such that exists only a prime number $p$ of the form $u^2+2au+b$ with $u$ integer. > > > I could only think that: We can write the form of prime number $p$ as $u^2+2au+b = (u + a)^2 - (a^2 - b)$ but I don't know how to continue.
2017/12/27
[ "https://math.stackexchange.com/questions/2581650", "https://math.stackexchange.com", "https://math.stackexchange.com/users/299420/" ]
ok. In both cases $y = \frac{p - 1}{2}$ and we choose $(a^2 - b) = c^2$ and $c^2 = \frac{p - 1}{2}$.
952,825
I am having 9 audio CD's to be used The first CD has the software to run the remaining 8 Cd's.The CD1 has an audio file and its exercise continues to the next CD i.e CD2 and so on it continues to CD8. There are no of issues handling multiple CD's 1. Its time consuming to remove 1 Cd after another. 2. Requires care while removing it from the packet and placing in the optical drive. 3. Possibility of misplacing the CD. So how can I avoid this cumbersome process and also remove the need of a CD if possible.Also would it make a difference with the type of data stored i.e an audio file,video file,etc. I am looking for a possible solution which is compatible with Windows 10. Tried the ripping software below and got an error just at the end of the disk. [![Saving could not completed.Could not read from disc.(Sector235480) ](https://i.stack.imgur.com/c8fX8.png)](https://i.stack.imgur.com/c8fX8.png) Output format:Mp3 BitRate:192Kbps
2015/08/08
[ "https://superuser.com/questions/952825", "https://superuser.com", "https://superuser.com/users/370953/" ]
Install a CD ripper software (like [this](http://www.ashampoo.com/dl/0710/ashampoo_burningstudio6_free_sm.exe) one), and rip the contents of every one of the 9 CD's (select Burn or Rip music --> Rip audio CD). The program will then copy the audio and you can then move the files to a USB key.
38,726,377
I know the basics of react, and did some of my personal projects on react. Now I am starting with [react-native](https://facebook.github.io/react-native/). So I created a new project and ran the `run-android` command. It did all the required processing and launched the emulator ( I am using Genymotion android emulator), ``` react-native init AwesomeProject cd AwesomeProject react-native run-android ``` After that in the emulator I enabled Hot reloading. Opened up the project and changed the code a bit. Then into the emulator, I pressed r (twice), it says `fetching bundle`. But I get the same thing. Nothing is changed. The changes are not updated. So, I closed the terminal and again ran this same command ``` react-native run-android ``` Then... it showed the changes. I have no idea what is wrong here. I saw [this post](https://stackoverflow.com/questions/38181670/hot-reloading-issue-about-developing-react-native-on-windows-envioment) and thought it might help. But it didn't. What am I doing wrong? I am using react-native 0.30.0, and Node v6.3.1. If it helps I am on windows 7, and running a nexus 6P as the Genymotion android emulator.
2016/08/02
[ "https://Stackoverflow.com/questions/38726377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2018197/" ]
Answering my own question. [This post](https://github.com/facebook/react-native/issues/7257) helped me. Inside this file \node\_modules\react-native\node\_modules\node-haste\lib\FileWatcher\ **index.js** 1. I had to increase `MAX_WAIT_TIME` (mine I changed from 120000 to 360000). 2. Also had to change This ``` key: '_createWatcher', value: function _createWatcher(rootConfig) { var watcher = new WatcherClass(rootConfig.dir, { glob: rootConfig.globs, dot: false }); return new Promise(function (resolve, reject) { var rejectTimeout = setTimeout(function () { return reject(new Error(timeoutMessage(WatcherClass))); }, MAX_WAIT_TIME); watcher.once('ready', function () { clearTimeout(rejectTimeout); resolve(watcher); }); }); } ``` into ``` key: '_createWatcher', value: function _createWatcher(rootConfig) { var watcher = new WatcherClass(rootConfig.dir, { glob: rootConfig.globs, dot: false }); return new Promise(function (resolve, reject) { const rejectTimeout = setTimeout(function() { reject(new Error([ 'Watcher took too long to load', 'Try running `watchman version` from your terminal', 'https://facebook.github.io/watchman/docs/troubleshooting.html', ].join('\n'))); }, MAX_WAIT_TIME); watcher.once('ready', function () { clearTimeout(rejectTimeout); resolve(watcher); }); }); } ``` Now after this changes, any code changes I make, I don't even have to press R twice, it automatically changes. I hope this might help a noob like me. Thank you.
42,191,345
I am new in django framework and I am trying to make an api for "register" where i want to insert data into db after execution but unable to do so . I am trying to create the object of auth\_user and trying to do `session.add(auth_user_object)` but it is not giving any error and even not adding data to mysql db. I am able to get(fetch) data from db . all the tables are created . then i am doing `inspect db` and get the db table class and modify it according to sqlalchemy. but I am unable to add data to the db tables using sqlalchemy . please help me. what is best approach to do so. my models.py ``` from __future__ import unicode_literals from django.db import models from sqlalchemy import * from sqlalchemy import types from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import * # Create your models here. Base = declarative_base() class Designation(Base): __tablename__='designation' id = Column(autoincrement=True,primary_key=True) designation_name = Column(String) designation_desc = Column(String) class UAuthUser(Base): __tablename__='auth_user' id = Column(autoincrement=True,primary_key=True) password = Column(String) last_login = Column(DateTime) is_superuser = Column(Integer) username = Column(String) first_name = Column(String) last_name = Column(String) email = Column(String) is_staff = Column(Integer) is_active = Column(Integer) date_joined = Column(DateTime) fcm_token = Column(String) designation_id = Column(Integer) ForeignKeyConstraint(['designation'], ['designation.id'] ``` my views.py ``` from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from django.shortcuts import render from designation.models import * #from designation.serializers import * from sqlalchemy.orm import * from sqlalchemy import Column, String, Integer, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import * from sqlalchemy.orm import sessionmaker import sqlalchemy, sqlalchemy.orm import urllib import urllib2 import json from datetime import datetime import collections import requests from sqlalchemy import create_engine import MySQLdb import mysql.connector def mysqlconnection(db): dialect = 'mysql' username = 'root' password = '' server = 'localhost' port = '3306' database = db url=dialect+'://'+username+':'+password+'@'+server+':'+port+'/'+database try: engine = create_engine(url) Session = sqlalchemy.orm.sessionmaker(bind=engine) session = Session() return session except: return ("Could not establish connection") # def mysqlCursor(db): # cnx = mysql.connector.connect(database='db') # cursor = cnx.cursor(raw=True, buffered=True) @api_view(['GET', 'POST']) def designation(request): session = mysqlconnection('hrdb') #query = session.query(Designation.id,Designation.designation_name,Designation.designation_desc).all() new_designation=Designation(id=3,designation_name='uday',designation_desc='shankar') session.add(new_designation) session.bulk_save_objects(new_designation) #session.commit() session.close() return Response('query') @api_view(['GET', 'POST']) def register(request): session = mysqlconnection('hrdb') password1 = "jhg$" last_login1 = "2017-02-08 16:12:52.822000" is_superuser1 = 0 username1 = "bibek_n" first_name1 = "bibek" last_name1 = "neupane" email1 = "vivek@gmail.com" is_staff1 = 0 is_active1 = 1 date_joined1 = "2017-02-08 16:12:52.822000" fcm_token1 = "abc" designation_id1 = 1 new_user = UAuthUser(password = password1,last_login = last_login1,is_superuser= is_superuser1,username = username1,first_name = first_name1,last_name = last_name1,email = email1,\ is_staff = is_staff1,is_active = is_active1,date_joined= date_joined1,fcm_token = fcm_token1,designation_id = designation_id1) session.add(new_user) #query = session.query(AuthUser).insert() #session.commit() session.close() return Response('query') ```
2017/02/12
[ "https://Stackoverflow.com/questions/42191345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5251686/" ]
by mistake i was not giving data type to the Id thats why the error was comming.
6,723,860
> > **Possible Duplicate:** > > [How to efficiently count the number of keys/properties of an object in JavaScript?](https://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascrip) > > > ``` var array = [{key:value,key:value}] ``` How can i find the total number of keys if it's an array of Object. When i do check the length of the array, it gives me one.
2011/07/17
[ "https://Stackoverflow.com/questions/6723860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733644/" ]
If you want to know the number of unique properties of `Object`s in an `Array`, this should do it... ``` var uniqueProperties = []; for (var i = 0, length = arr.length; i < length; i++) { for (var prop in arr[i]) { if (arr[i].hasOwnProperty(prop) && uniqueProperties.indexOf(prop) === -1 ) { uniqueProperties.push(prop); } } } var uniquePropertiesLength = uniqueProperties.length; ``` [jsFiddle](http://jsfiddle.net/alexdickson/exdYG/). Note that an `Array`'s [`indexOf()`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf) doesn't have the best browser support. You can always [augment the `Array` prototype](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf#Compatibility) (though for safety I'd make it part of a `util` object or similar).
24,303,764
I have a select box and I styled it to look like an Android `Spinner`. See the [fiddle](http://jsfiddle.net/pUsN8/1). The problem is that I can not figure out how to make the triangle blue when the select is focused. Can anyone help?
2014/06/19
[ "https://Stackoverflow.com/questions/24303764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1373050/" ]
The problem is you are trying to travel around the DOM the wrong way. You want a nephew to affect an uncle, and you can't do that with CSS alone. However, if you make div.triangle a sibling of select, then your CSS will work. You just need to change the positioning of the .triangle CSS <http://jsfiddle.net/wildandjam/6DkN6/> ``` <div class="dataInputComboboxWrap"> <div class="dataInputComboboxContainer"> <select class="dataInputCombobox" > <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> <option>Option 4</option> </select> <div class="triangle"> </div> </div> ``` And to make the triangle viewable inside the Container: ``` .triangle { left: -50px; } ```
68,554,096
I want to return the data from second activity to first activity using intent when click the OnAddClicked button in second activity, but what I done was not working. The data that I return to first activity is null and I have no idea about this. Can anyone help me to solve this problem? First Activity: ``` public class CartView extends AppCompatActivity { ActivityCartViewBinding binding; public CartView.MyClickHandler handler; GridView view_listView; String Default_curr; String itemgroup; String itemtype; String uprice; String quantity; ACDatabase db; List<AC_Class.Item> s_item = new ArrayList<>(); AC_Class.InvoiceDetails invoiceDetails; AC_Class.Item item; String substring = ""; EditText searchEditText; Button All; Button Type; Button Group; ArrayAdapter<String> adapter; int i = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_cart_view); // Action Bar ActionBar actionBar = getSupportActionBar(); actionBar.setTitle("Catalog"); actionBar.setDisplayHomeAsUpEnabled(true); searchEditText = (EditText) findViewById(R.id.searchField); UIUtil.hideKeyboard(this); UIUtil.showKeyboard(this, searchEditText); db = new ACDatabase(this); invoiceDetails = new AC_Class.InvoiceDetails(); item = new AC_Class.Item(); handler = new MyClickHandler(this); binding.setHandler(handler); All = (Button) findViewById(R.id.button1); Type = (Button) findViewById(R.id.button2); Group = (Button) findViewById(R.id.button3); view_listView = (GridView) findViewById(R.id.GridView); All.setVisibility(View.GONE); Type.setVisibility(View.GONE); Group.setVisibility(View.GONE); getData(""); searchEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {} @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {} @Override public void afterTextChanged(Editable s) { getData(s.toString().trim()); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.ctlg_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); /*if (id == android.R.id.home) { onBackPressed(); return true; }*/ if (id == R.id.cart) { Intent new_intent = new Intent(CartView.this, CartList.class); new_intent.putExtra("invoiceDetail", invoiceDetails); startActivityForResult(new_intent,3); } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); getData(""); } public void getData(String substring) { Cursor data = db.getItemLike(substring, 0); if (data.getCount() > 0){ s_item.clear(); while (data.moveToNext()) { try { AC_Class.Item item = new AC_Class.Item(data.getString(0), data.getString(1), data.getString(2), data.getString(3), data.getString(4), data.getString(5), data.getString(6), data.getString(7), data.getString(8), data.getFloat(9), data.getFloat(10), data.getFloat(11), data.getFloat(12), data.getFloat(13), data.getFloat(14), data.getString(15), data.getString(16), data.getFloat(17), data.getString(18),data.getFloat(19),data.getFloat(20)); s_item.add(item); } catch (Exception e) { Log.i("custDebug", "error reading image: "+e.getMessage()); } } CartViewListAdapter arrayAdapter = new CartViewListAdapter(this, s_item); view_listView.setAdapter(arrayAdapter); Cursor dcurren = db.getReg("6"); if(dcurren.moveToFirst()){ Default_curr = dcurren.getString(0); } view_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String itemcode = ((AC_Class.Item)parent.getItemAtPosition(position)).getItemCode(); String uom = ((AC_Class.Item)parent.getItemAtPosition(position)).getUOM(); AC_Class.Item sa =((AC_Class.Item) parent.getItemAtPosition(position)); //Intent item_intent = new Intent(); Intent item_intent = new Intent(CartView.this, ItemDetail.class); item_intent.putExtra("ItemKey",itemcode); item_intent.putExtra("ItemUOMKey",uom); item_intent.putExtra("Items",sa); //setResult(4, item_intent); startActivity(item_intent); //finish(); } }); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case 1: if (resultCode == 1) { itemtype = data.getStringExtra("TypeKey"); if (itemtype != null) { getTypedata(); } } break; case 2: if (resultCode == 1) { itemgroup = data.getStringExtra("GroupKey"); if(itemgroup != null){ getGroupdata(); } } break; case 3: if (resultCode == 1) { AC_Class.Item i = data.getParcelableExtra("Item"); uprice = data.getStringExtra("Price"); quantity = data.getStringExtra("Quantity"); if (i != null) { invoiceDetails.setItemCode(i.getItemCode()); invoiceDetails.setItemDescription(i.getDescription()); invoiceDetails.setUPrice(Double.valueOf(i.getPrice())); invoiceDetails.setUOM(i.getUOM()); //invoiceDetails.setUPrice(Double.valueOf(uprice)); invoiceDetails.setQuantity(Double.valueOf(quantity)); } } break; } } } ``` SecondActivity: ``` public class ItemDetail extends AppCompatActivity { ActivityItemDetailBinding binding; AC_Class.Item items; AC_Class.ItemUOM itemuom; AC_Class.Cart cart; AC_Class.InvoiceDetails invoiceDetails; ACDatabase db; String Item; String ItemUOM; String Default_curr; Intent pintent; EditText etQty; String default_loc; List<AC_Class.Item> c_item = new ArrayList<>(); MyClickHandler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_item_detail); itemuom = new AC_Class.ItemUOM(); items = new AC_Class.Item(); invoiceDetails = new AC_Class.InvoiceDetails(); cart = new AC_Class.Cart(); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); db = new ACDatabase(this); pintent = getIntent(); //substring = pintent.getStringExtra("substring"); Item = pintent.getStringExtra("ItemKey"); ItemUOM = pintent.getStringExtra("ItemUOMKey"); handler = new MyClickHandler(this); binding.setHandler(handler); Cursor loc = db.getReg("7"); if(loc.moveToFirst()){ default_loc = loc.getString(0); } items = pintent.getParcelableExtra("Items"); binding.setItem(items); binding.setInvoicedetail(invoiceDetails); binding.quantity.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { etQty = (EditText)findViewById(R.id.quantity); String qty = etQty.getText().toString(); if(qty.length() > 0) { invoiceDetails.setQuantity(Double.valueOf(qty)); //Calculation(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: { onBackPressed(); return true; } } return super.onOptionsItemSelected(item); } public class MyClickHandler { Context context; public MyClickHandler(Context context) { this.context = context; } public void OnAddClicked(View view) { //Intent new_intent = new Intent(context, CartList.class); Intent new_intent = new Intent(context,CartView.class); new_intent.putExtra("Item", items); new_intent.putExtra("Quantity",invoiceDetails.getQuantity()); new_intent.putExtra("Price",invoiceDetails.getUPrice()); setResult(1, new_intent); finish(); } } } ```
2021/07/28
[ "https://Stackoverflow.com/questions/68554096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15782726/" ]
You could use your own formatting logic, e.g. ```py a = (1,2,3) s = ','.join([str(x) for x in a]) print(s) # 1,2,3 a = (1,) s = ','.join([str(x) for x in a]) print(s) # 1 ```
14,700,931
I am showing and hiding a div which contains loading/waiting gif image. on click of a button i call `$("#div").show()` and `.hide()` at the end of click function. but image is not showing generally. When I put break point next to `.show()` line it shows the image. I also tried `.css("display","")`, but it wont worked. Please suggest any other way, or tell me what could be the problem. Thanks. my code looks like, below ``` $("#button").click(function(){ $("#div").show(); // showing image so that user will know that a process is going on. //other working code $("#div").hide(); // hiding will indicate process completion }); ```
2013/02/05
[ "https://Stackoverflow.com/questions/14700931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2041896/" ]
Javascript is single threaded and the same thread is shared for UI rendering and script execution. Because of the way the browsers does optimization you are not seeing the show() and hide() effects. You could make use of JQuery promise mechanism to solve your problem. Examples [here](http://api.jquery.com/promise/) Instead of doing this way > > 1) show the DIV > > > 2) execute some code > > > 3) hide the DIV > > > you will de doing this > > 1) show the div > > > 2) When 'show' is complete > > > > ``` > 2.1) execute your code, > 2.2) hide the DIV > > ``` > > I created a JSbin working example [here](http://jsbin.com/umecip/14/edit)
51,709
From what I hear about globular clusters, they are primarily composed of very hot giant stars, which are not the most conducive for life as we know it. Main sequence stars like our own, due to their relatively long lifespans and generally weaker radiation, are a much better candidate. So, is it possible for a globular cluster to exist, but one composed primarily of small main-sequence stars such G-type, M-type and K-type dwarfs?
2023/01/24
[ "https://astronomy.stackexchange.com/questions/51709", "https://astronomy.stackexchange.com", "https://astronomy.stackexchange.com/users/48733/" ]
The opposite is true. You should check your sources. Globular clusters do primarily consist of small main-sequence stars. Globular clusters are believed to be formed in the halo of the Galaxy at the same time as the Galaxy formed itself (although their formation still is poorly understood). Regardless of their formation process, any massive star inside the globular clusters will long have gone supernova or red giant and ceased to exist (or turned into white dwarfs). So virtually every star you see in a globular cluster is a sub-dwarf main sequence star, G-type with a life time exceeding 10 billion years being the most massive which could still be around. See also <https://en.wikipedia.org/wiki/Globular_cluster>
58,893,146
I am developing a database on online quiz management * one table stdinfo stores usernames and student details * table testinfo stores the testid name subjects and their marking schemes(separate for each subject) in form of multiple rows like ![see this](https://i.stack.imgur.com/C1ikT.png) * and one table question has all the questions with their qids * and one table records the responses of students Now there is a column marks in responses which displays the marks obtained in that question. Since i want to generate the result i have already inserted the responses and their ids/usernames. Now i want to insert marks for calculate result; what it should do * set marks=0 where the response is null ; * set marks=posmark obtained from the testinfo table for respective subject if the response is correct * set marks=negmark obtained from the testinfo table for respective subject if the response is incorrect table structures are given below; ![responses](https://i.stack.imgur.com/3TB3J.png) ![testinfo](https://i.stack.imgur.com/wvhpB.png) ![question](https://i.stack.imgur.com/Yzy8c.png)
2019/11/16
[ "https://Stackoverflow.com/questions/58893146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10706941/" ]
see the answer for your question [here][1] <https://forums.mysql.com/read.php?20,85813,85816#msg-85816> or look at this: ``` UPDATE a INNER JOIN b USING (id) SET a.firstname='Pekka', a.lastname='Kuronen', b.companyname='Suomi Oy',companyaddress='Mannerheimtie 123, Helsinki Suomi' WHERE a.id=1; ```
217,998
I know he made Snape's life miserable, but he seemed to particularly hate him in book three, hunting him and calling dementors to destroy his soul, even going against Dumbledore to punish Sirius. Did he hate him then because he thought Sirius had sent You-know-who after Lilly.
2019/08/25
[ "https://scifi.stackexchange.com/questions/217998", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/118727/" ]
Snape hated Sirius mainly for bullying him. =========================================== The most likely reason that Snape hated Sirius is because Sirius bullied him relentlessly while they were attending Hogwarts. Though it’s possible that Snape, like most everyone else at the time (including Order members) thought Sirius was responsible for Lily’s death and hated him for it, Snape’s hatred for Sirius isn’t rooted mainly in blaming him for Lily’s death. Snape hated Sirius before Lily was ever in any sort of danger from the Dark Lord, and continued to hate him after the Order learned that Pettigrew, not Sirius, was the one who betrayed the Potters. Therefore, it’s far more likely Snape’s main reason for hating Sirius was that Sirius bullied him. Snape hated Sirius from before Lily died. ========================================= Snape’s hatred for Sirius predates Lily’s death by several years. When they were classmates at Hogwarts, Sirius bullied Snape as a form of entertainment. > > “This’ll liven you up, Padfoot,’ said James quietly. ‘Look who it is …’ > > > Sirius’s head turned. He became very still, like a dog that has scented a rabbit. > > > ‘Excellent,’ he said softly. *‘Snivellus.’*” > *- Harry Potter and the Order of the Phoenix, Chapter 28 (Snape’s Worst Memory)* > > > Sirius seemed to have a habit of physically attacking Snape. > > “Snape lay panting on the ground. James and Sirius advanced on him, wands raised, James glancing over his shoulder at the girls at the water’s edge as he went.” > *- Harry Potter and the Order of the Phoenix, Chapter 28 (Snape’s Worst Memory)* > > > Additionally, Sirius enjoyed insulting Snape. > > “How’d the exam go, Snivelly?’ said James. > > > ‘I was watching him, his nose was touching the parchment,’ said Sirius viciously. ‘There’ll be great grease marks all over it, they won’t be able to read a word.” > *- Harry Potter and the Order of the Phoenix, Chapter 28 (Snape’s Worst Memory)* > > > Therefore, it seems clear that Snape’s hatred of Sirius dated back to their Hogwarts years, when Sirius (along with James) bullied him relentlessly. In fact, since the first time they met, it was clear that Snape and Sirius were unlikely to get along. > > “No,’ said Snape, though his slight sneer said otherwise. ‘If you’d rather be brawny than brainy –’ > > > ‘Where’re you hoping to go, seeing as you’re neither?’ interjected Sirius. > > > James roared with laughter. Lily sat up, rather flushed, and looked from James to Sirius in dislike.” > *- Harry Potter and the Deathly Hallows, Chapter 33 (The Prince’s Tale)* > > > During these years, Snape had no reason to think Sirius was any danger to Lily, but he certainly was a danger to Snape himself. He hated him after he was proven innocent. ========================================== Also, once Sirius was known to be innocent by the Order, and its members knew he wasn’t responsible for betraying the Potters, it was clear that Snape and Sirius still hated each other. > > “A minute or two later, he pushed open the kitchen door to find Sirius and Snape both seated at the long kitchen table, glaring in opposite directions. The silence between them was heavy with mutual dislike.” > *- Harry Potter and the Order of the Phoenix, Chapter 24 (Occlumency)* > > > After it was clear Sirius wasn’t responsible for Lily’s death, Snape and Sirius were still almost about to duel each other in Grimmauld Place until more people came in. > > “He and all the other Weasleys froze on the threshold, gazing at the scene in front of them, which was also suspended in mid-action, both Sirius and Snape looking towards the door with their wands pointing into each other’s faces and Harry immobile between them, a hand stretched out to each, trying to force them apart. > > > ‘Merlin’s beard,’ said Mr Weasley, the smile sliding off his face, ‘what’s going on here?’ > > > Both Sirius and Snape lowered their wands. Harry looked from one to the other. Each wore an expression of utmost contempt, yet the unexpected entrance of so many witnesses seemed to have brought them to their senses.” > *- Harry Potter and the Order of the Phoenix, Chapter 24 (Occlumency)* > > > This makes it clear that the knowledge of Sirius not being responsible for Lily’s death didn’t make Snape stop hating him or lessen his hatred to any considerable degree.
54,935,501
I found the following in the web about the performance of CRCs: > > Primitive polynomial. This has optimal length for HD=3, and good HD=2 > performance above that length. > > > I don't get it. Optimal length for HD=3 is understandable; but what does good HD=2 performance mean? AFAIK all CRCs have infinite data length at HD=2. So what does "good HD=2 performance above that length" for primitive polynomials mean?
2019/02/28
[ "https://Stackoverflow.com/questions/54935501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1421332/" ]
> > ... has optimal length for HD=3, and good HD=2 performance above that length. > > > The statement is poorly worded. I find it at the bottom of this web page under "Notation:" <https://users.ece.cmu.edu/~koopman/crc> In this and other articles I find, the abbreviation "HD" represents the minimum Hamming Distance for a CRC: for HD=k+1, then the CRC can detect any pattern of k bit errors in a message up to some length (as shown in the tables). As you stated, "all CRCs have infinite data length at HD=2". The usage of the phrase "good HD=2 performance above that length" is confusing. The web site above links to the web site below which includes the statement "HD=2 lengths are always infinite, and so are always left out of this list." <https://users.ece.cmu.edu/~koopman/crc/notes.html> --- [Wiki hamming distance](https://en.wikipedia.org/wiki/Hamming_distance#Error_detection_and_error_correction) explains the relationship between bit error detection and Hamming distance: "a code C is said to be k error detecting if, and only if, the minimum Hamming distance between any two of its codewords is at least k+1" As you stated, "all CRCs have infinite data length at HD=2", meaning all CRCs can detect any single bit error regardless of message length. As for "optimal length for HD=3", which means being able to detect a 2 bit error, consider a [linear feedback shift register](https://en.wikipedia.org/wiki/Linear-feedback_shift_register) based on the CRC polynomial, initialized with any non-zero value, if you cycle the register enough times, it will end up back with that initial value. For a n bit CRC based on a n+1 bit primitive polynomial, the register will cycle through all 2^n - 1 non-zero values before repeating. The maximum length of the message (which is the length of data plus the length of CRC) where no failure to detect a 2 bit error can occur is 2^n - 1. For a message of length 2^n or greater, then for any "i", if bit[0+i] and bit[(2^n)-1+i] are in error, the primitive CRC will fail to detect the 2 bit error. If the CRC polynomial is not primitive, the the maximum length for failproof 2 error bit detection will be decreased, and not "optimal". For a linear feedback shift register based on any CRC polynomial, initialized to any non-zero value, no matter how many times it it cycled, it will never include a value of zero. This is one way to explain why "all CRCs have infinite data length at HD=2" (are able to detect single bit errors).
60,361,431
**CONTEXT** I am developing an app where, on a certain moment, a bunch of images are added to the screen. These images are stored on a SQLite database. --- **HOW IT WORKS** I have a `for` loop which iterates over each entity that has its own image. Inside the loop, I obtain a random position on the screen, and alongside the image of the current entity, I add a custom `View` on that random position. --- **PROBLEM** The `for` loop iterates over all data gathered from the database, gets coordinates and images correctly, and no `Exception` is thrown. However, in the main layout, only the image of the first entity is shown, although `addView` is being executed for each one of all entities. The image appearing is only shown once. --- **SNIPPETS** Main activity method: ``` // Método que establece el estado inicial de la aplicación // TODO: Sólo se ve la cereza private void estadoInicial() { // Recorremos cada fruta obtenida for (int i = 0; i < this.contenedorFrutasOriginal.size(); i++) { // Obtenemos la fruta de la iteración actual DTOFruta frutaActual = this.contenedorFrutasOriginal.get(i); if (frutaActual.getImagen() != null) { // Obtenemos una posición aleatoria en la pantalla DTOPunto posicionAleatoria = this.objLogicaVistas.ObtenerCoordenadaAleatoria(getWindowManager().getDefaultDisplay()); // Creamos una imagen a partir de la fruta DTOImagen imagenFruta = new DTOImagen(this, new Paint(), frutaActual.getImagen(), posicionAleatoria); // Añadimos la imagen a la pantalla this.layoutPrincipal.addView(imagenFruta); } } } ``` Method that obtains a random coordinate from the screen: ``` // Método que obtiene una coordenada aleatoria en la pantalla recibida public DTOPunto ObtenerCoordenadaAleatoria(Display pantalla) { // Obtenemos el tamaño de la pantalla Point tamanoPantalla = new Point(); pantalla.getSize(tamanoPantalla); // Obtenemos unos valores para los ejes x e y aleatorios float xAleatorio = new Random().nextFloat() * tamanoPantalla.x; float yAleatorio = new Random().nextFloat() * tamanoPantalla.y; // Creamos el punto aleatorio a partir de los valores obtenidos return new DTOPunto(xAleatorio, yAleatorio); } ``` Class for the image getting drawn on the screen: ``` // Clase que representa una vista con una imagen @SuppressLint("ViewConstructor") public class DTOImagen extends View { // Atributos private Paint brocha; private byte[] imagen = null; private DTOPunto coordenadas; // Controladores private boolean arrastrando; // Propiedades public Bitmap getImagenBitmap() { return BitmapFactory.decodeByteArray(this.imagen, 0, this.imagen.length); } // Constructor public DTOImagen(Context context, Paint brocha, byte[] imagen, DTOPunto coordenadas) { super(context); // Obtenemos los datos de la imagen this.brocha = brocha; if (imagen != null) { this.imagen = imagen; } this.coordenadas = coordenadas; // Asignamos los controladores de la imagen this.arrastrando = false; } // Método que controla las acciones a realizar al tocar la vista en pantalla @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { // Comprobamos el evento realizado switch (event.getAction()) { // Se ha tocado la pantalla case MotionEvent.ACTION_DOWN: // Obtenemos el hitbox de la vista RectF hitbox = this.obtenerHitbox(); // Comprobamos si se ha tocado dentro del hitbox de la vista if (hitbox.contains(event.getX(), event.getY())) { // La vista se va a arrastrar this.arrastrando = true; } break; // Se está arrastrando la vista case MotionEvent.ACTION_MOVE: // Comprobamos si se está arrastrando la vista if (this.arrastrando) { // Actualizamos las coordenadas de la vista this.coordenadas.setX(event.getX()); this.coordenadas.setY(event.getY()); // Invalidamos la vista para que se redibuje this.invalidate(); } break; // Se ha dejado de tocar la vista case MotionEvent.ACTION_UP: // La imagen se deja de arrastrar this.arrastrando = false; break; } return true; } // Método que dibuja la vista @SuppressLint("DrawAllocation") @Override protected void onDraw(Canvas canvas) { // Comprobamos que haya imagen if (this.imagen != null) { // Dibujamos la imagen en las coordenadas correspondientes canvas.drawBitmap(this.getImagenBitmap(), this.coordenadas.getX(), this.coordenadas.getY(), this.brocha); } } // Método que obtiene el hitbox de una imagen private RectF obtenerHitbox() { // Obtenemos las mitades de la altura y ancho de la imagen float ancho = this.getImagenBitmap().getWidth(); float altura = this.getImagenBitmap().getHeight(); // Obtenemos las paredes de la vista float paredIzquierda = this.coordenadas.getX(); float paredDerecha = this.coordenadas.getX() + ancho; float paredArriba = this.coordenadas.getY(); float paredAbajo = this.coordenadas.getY() + altura; // Hitbox de la vista return new RectF(paredIzquierda, paredArriba, paredDerecha, paredAbajo); } } ``` `layoutPrincipal` XML: ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".capa_vistas.ActPrincipal"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:background="@mipmap/fondo" android:contentDescription="@null" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/layoutPrincipal" android:orientation="vertical"> </LinearLayout> </RelativeLayout> ``` --- **DEBUGGING** The following image shows `layoutPrincipal` children after the `for` loop: [![Layout children after adding views](https://i.stack.imgur.com/oCmKC.png)](https://i.stack.imgur.com/oCmKC.png) PD: `DTOPunto` is a class that represents a 2D point, it only has a couple of `float`, for X and Y axis values. 2nd PD: On the last iteration, I found that the layout has all previous images as children, so it looks like those are added correctly.
2020/02/23
[ "https://Stackoverflow.com/questions/60361431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10583304/" ]
according to your desired output you want to change the `intalValue` during `sampleList` iteration: ``` finalList = [] intialValue = 30 intialList = [intialValue] eff = 0.25 sampleList = [12,3,1,4,25,3,2,22,12,32,34,2,1,5,7] for a in sampleList: if a < 10: calculated_value = intialValue + intialValue * eff else: calculated_value = intialValue - intialValue * eff intialValue = calculated_value finalList.append(intialValue) intialList.append(intialValue) print(intialList) print(finalList) ``` **output:** ``` [30, 22.5, 28.125, 35.15625, 43.9453125, 32.958984375, 41.19873046875, 51.4984130859375, 38.623809814453125, 28.967857360839844, 21.725893020629883, 16.294419765472412, 20.368024706840515, 25.460030883550644, 31.825038604438305, 39.78129825554788] [22.5, 28.125, 35.15625, 43.9453125, 32.958984375, 41.19873046875, 51.4984130859375, 38.623809814453125, 28.967857360839844, 21.725893020629883, 16.294419765472412, 20.368024706840515, 25.460030883550644, 31.825038604438305, 39.78129825554788] ```
14,985,322
I know when Linq's `Any()` extension is used to determine if an enumerable has at least one element it will only consume a single element. But how does that work actually? Does it have to cast all items in the enumerable first, or does it just cast them one at a time, starting with the first and stopping there?
2013/02/20
[ "https://Stackoverflow.com/questions/14985322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/480118/" ]
`Any()` works on an `IEnumerable<T>` so no cast is required. It's implementation is very simple, it simply iterates through the enumerable and sees if it can find any elements matching the specified criteria.
265,617
Any field that I would expect a value (Like an orderNumber or customerNumber) I would set as not nullable. If I'm expecting the value of the field to be not null, shouldn't I also always have a constraint that does not allow for zero length strings or space only strings?
2020/04/22
[ "https://dba.stackexchange.com/questions/265617", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/37509/" ]
* If the sequence is used in the `DEFAULT` clause of the table column, it is enough to rename the sequence. That is because the `DEFAULT` clause is *not* stored as string, but as parsed expression tree (column `adbin` in catalog `pg_attrdef`). That expression tree does not contain the name of the sequence, but its object ID, which is unchanged by renaming the sequence. Tools like `psql`'s `\d` re-construct a string from the parsed expression, so the `DEFAULT` clause will appear to reflect the renaming. * If the sequence name is used elsewhere, like in your client code or in a PostgreSQL function, you would have to change the name in that code. PostgreSQL functions are stored as strings (column `prosrc` in catalog `pg_proc`), so renaming a sequence can make a function that uses the sequence fail. In this case, you would have to suspend activity until you have changed the code and renamed the sequence if you want to avoid errors.
34,985,305
Atom text editor adds this symbol to every empty line. Any idea what and why? [![enter image description here](https://i.stack.imgur.com/YQGMT.png)](https://i.stack.imgur.com/YQGMT.png)
2016/01/25
[ "https://Stackoverflow.com/questions/34985305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5657555/" ]
I'm on Ubuntu Linux and noticed the ^M (Carriage Return, Line Feed) during `git diff`. Somehow CRLF was selected at the bottom of the status bar: [![CRLF in Atom status bar](https://i.stack.imgur.com/Nzipz.png)](https://i.stack.imgur.com/Nzipz.png) I simply clicked it and changed to LF: [![LF in Atom Status Bar](https://i.stack.imgur.com/Yb3Hs.png)](https://i.stack.imgur.com/Yb3Hs.png) It seems to be set on a file-by-file basis so will need to be changed for each problem file. --- In my case somehow all the line endings had been changed so `git diff` was a sea of red. I used the following to identify 'real' changes: ``` git diff --ignore-space-at-eol ``` However, `git commit` would still bury the 'real' changes in commit history so I: 1. ran `git stash save` 2. changed line endings in atom 3. ran `git commit -am "fix line endings"` 4. ran `git stash apply` Now the line endings are gone and commits can be made on a precise diff.
50,927
I have SharePoint list named "XXXXXXXXXXXX". when select any list item then the navigation removed and the options pane will appear. i want the navigation remains same even if i select list or list item. please reply as soon as possible. I want this when i select list/list item : ![enter image description here](https://i.stack.imgur.com/hdX1Z.png) I get this when i select list/list item : ![enter image description here](https://i.stack.imgur.com/bUP10.png)
2012/11/06
[ "https://sharepoint.stackexchange.com/questions/50927", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/-1/" ]
Basically if I understand correctly you want to have the navigation still be available (beign seen) even if the ribbon is expanded when selecting a list item or list web part. Basically it is still on the page, but it is behind the ribbon, so i would suggest you play with css and move the navigation more down, or let the ribbon appear lower. So its up to you to chose, but the solution is changing css. Also you might investigate the javascript behind when expending the ribbon, so you might perfrom some extra task like changing css styles on the time when the ribbon is expanded and putting everything back when it is closed.
40,339,272
i have created a wheel and added the rotation now its rotating in the anticlockwise direction,how can it made to be rotated in the clockwise direction ``` using UnityEngine; using System.Collections; using System.Collections.Generic; public class Rotate : MonoBehaviour { public List<int> prize; public List<AnimationCurve> animationCurves; private bool spinning; private float anglePerItem; private int randomTime; private int itemNumber; void Start(){ spinning = false; anglePerItem = 360/prize.Count; } void Update () { if (Input.GetKeyDown (KeyCode.Space) && !spinning) { randomTime = Random.Range (5, 10); itemNumber = Random.Range (0, prize.Count); float maxAngle = 360 * randomTime + (itemNumber * anglePerItem); StartCoroutine (SpinTheWheel (1 * randomTime, maxAngle)); } } IEnumerator SpinTheWheel (float time, float maxAngle) { spinning = true; float timer = 0.0f; float startAngle = transform.eulerAngles.z; maxAngle = maxAngle - startAngle; int animationCurveNumber = Random.Range (0, animationCurves.Count); Debug.Log ("Animation Curve No. : " + animationCurveNumber); while (timer < time) { //to calculate rotation float angle = maxAngle * animationCurves [animationCurveNumber].Evaluate (timer / time) ; transform.eulerAngles = new Vector3 (0.0f, 0.0f, angle + startAngle); timer += Time.deltaTime; yield return 0; } transform.eulerAngles = new Vector3 (0.0f, 0.0f, maxAngle + startAngle); spinning = false; Debug.Log ("Prize: " + prize [itemNumber]);//use prize[itemNumnber] as per requirement } } ``` also now it starts rotates and after the time finish it suddenly stops, how can it be made like ,it stops like decreasing the speed
2016/10/31
[ "https://Stackoverflow.com/questions/40339272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6777441/" ]
That's because the quantity that's being assigned to `fruits[0].quantity` is a `Number`. If double quotes `"` will appear if this quantity is a `String`. So what you can do is typecast this Number to `String` using `String()` function of `javascript`. ``` fruits[0].quantity = String(Number(fruits[0].quantity) + Number($("#qty").val())); ``` **Output** ``` {name: "bananas", quantity: "5"} ```
7,550,944
i extended a panel containing ``` -Panel -Toolbar with button ``` and i registered it as a xtype using Ext.reg().There is one more panel in which i want to add the registered xtype and did it. How can i add/remove a component/html content dynamically to the outer panel on button click. Thanks in advance.
2011/09/26
[ "https://Stackoverflow.com/questions/7550944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/956448/" ]
I hope it will help you : ``` var component = ...; var position = 0; component.insert(position, new Ext.Panel({html : "inserted"})); component.doComponentLayout(); ```
393,956
I tried `ls -l /proc/17301504` there is no exe which gives me full path to command. Is there a way to get the full path of command in Aix 5 and above as in Linux? There is a.out in `/proc/17301504/object` which has same checksum as the command, but does not gives the full path.
2017/09/23
[ "https://unix.stackexchange.com/questions/393956", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/252519/" ]
The `/proc` filesystem is inherently not portable between operating systems. There are Unices where it does not exist at all. The `/proc` filesystem on AIX is documented here: <https://www.ibm.com/support/knowledgecenter/en/ssw_aix_61/com.ibm.aix.files/proc.htm> About the `a.out` file in the `object` subdirectory, it says: > > [...] The name `a.out` also appears in the directory as a synonym for the executable file associated with the text of the running process. > > > The `object` directory makes it possible for a controlling process to get access to the object file and any shared libraries (and consequently the symbol tables), without the process first obtaining the specific path names of those files. > > > This means that accessing the `a.out` file in that structure is more or less the opposite of what you want to do. It allows a user program to access the executable of a process without knowing its full path. There is also structures in `/proc` on AIX that contains the basename of the executable, but again, this is not what you're interested in. Since a process can set its own zeroth command line argument (the name of the process that shows up in `ps`), using `ps` would also not be a surefire solution to find the absolute path to the running executable, even if it was executed with a full path. What you *could* do is to hunt down the executable by its inode. An example of how to do this is described in the currently accepted answer to the question "[How to identify executable path with its PID on AIX 5 or more](https://unix.stackexchange.com/questions/109175/how-to-identify-executable-path-with-its-pid-on-aix-5-or-more)". It may also be good to ask yourself why you need this information from querying a *running* process, as it's usually clear from studying a script or program exactly what external utilities it is invoking.
64,910
I have posted numerous homebrew features on Role-playing Games Stack Exchange, and I have used advice gotten from that site to balance most of them. If, one day, I publish the subclass, would I be required to give any or all of the following credits? * To the RPG.SE website as a whole * To the individual users that gave feedback * Just to the users whose feedback I used Or would I not be required to give any credit?
2021/05/11
[ "https://law.stackexchange.com/questions/64910", "https://law.stackexchange.com", "https://law.stackexchange.com/users/-1/" ]
It's complicated ---------------- ### You still own your own posts First off, you own everything that *you* originally created. Posting it on Stack Exchange doesn't affect your rights to your own content. ### Incorporating suggestions If you copy any of the text from posts that were created by others, you must comply with the CC BY-SA license. The exact version will depend on when the content was posted, and can be viewed by clicking the "Share" link or viewing the post's timeline via the clock icon on the left. Currently, new posts are licensed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/), which requires you to (basically) provide attribution with the creator's name, a link back to the content, and an indication of whether changes were made. A more detailed description of the exact requirements is [here](https://wiki.creativecommons.org/wiki/License_Versions#Detailed_attribution_comparison_chart). You would also be required to license the work that you incorporated it into under the same license. However, [game mechanics aren't copyrightable](https://law.stackexchange.com/a/4653/32651). If you merely used mechanics suggested in the posts without actually using the actual creative expression (for instance, names or description text) from the posts, you would not be required to provide any attribution or use any particular license, because you didn't use any copyrightable material from the post. ### A thank-you would still be nice All that said, it's still a nice thing to do to provide some sort of informal thanks to those who provided valuable assistance, even when you're not legally required to do so.
5,215
After posting various questions (that are similar, but different - during the time frame permitted by the community, with a space of 40min between each), I received the following comments > > With 4 questions on the same topic asked by you within 2 hours, maybe chat would be a better alternative, until you can find a single useful question to ask. ([Source](https://philosophy.stackexchange.com/questions/77701/should-harm-be-answered-only-by-the-individual?noredirect=1#comment216282_77701)) > > > And > > It's more than 4. This user is also asking very similar questions on Politics.SE, and I've seen at least two cross-site dupes (one now deleted). ([Source](https://philosophy.stackexchange.com/questions/77701/should-harm-be-answered-only-by-the-individual?noredirect=1#comment216290_77701)) > > > Is it against the community to post multiple questions, even if they are related but different? [Accordingly to Meta](https://meta.stackexchange.com/a/4712/362304) and SE guidelines, I didn't find any opposing this behaviour, but I would appreciate your answers here. Eventually, [due to another user's suggestion](https://philosophy.stackexchange.com/questions/77699/should-freedom-of-speech-be-limited#comment216273_77699), I ended up cross-posting two questions that I shared in Philosophy SE (the second comment points that out, however in a question that I only shared here), on Politics SE (one of which was deleted).
2020/11/29
[ "https://philosophy.meta.stackexchange.com/questions/5215", "https://philosophy.meta.stackexchange.com", "https://philosophy.meta.stackexchange.com/users/35436/" ]
I guess there is no written rule against this as it is an unlikely event, more typically happening with blatantly off-topic spam. It is also generally good to open separate questions rather than mixing fundamentally different questions in the same post, so there cannot be a general rule to not make multiple posting in a short time. But when there is a big overlap between questions, that gives the impression that the asker is not writing out of curiosity or a need to know something, but for other purposes, e.g. to advertise a certain opinion and get attention. The motivation for a question is not generally a reason for downvote it closing, good questions can come out of this, but with that motivation, a lack of quality often also occurs. So I would think it risks creating a false impression when done inadvertently.
46,690,326
I'm building an Event App and would like to get All the Events on a certain date and then sort them by there location to me. How would Implement a request like this? This is what the Schema looks like: ``` var eventSchema = mongoose.Schema({ _id: { type: String, required: true }, name: { type: String, required: true }, start_time: { type: Date }, location: { type: { type: String }, coordinates: [] }, }); ``` I know I can query the location using the $near, i've managed to get this running. But I would like to first query for "start\_time" and then sort by the events on that date by their distance to me. Any Suggestions would be very appreciated thanks ;)
2017/10/11
[ "https://Stackoverflow.com/questions/46690326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7101709/" ]
Use the `$geoNear` agg pipeline operator. It will return docs **in order of closeness to a point you specify**. You can tell `$geoNear` to further constraint the lookup to just your `start_time` (or any arbitrary query expression) with the `query` option in the call. Details here: <https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/>
33,050,043
I need an idea on how to call an activity that has a gridview from another activity. Basically, supposed my main activity has one button and when you click the button you are directed to another activity with the following sample code ``` public void onClick(View v){ if (v.getId() == R.id.button2) { Intent intent = new Intent(this, AnotherActivity.class); this.startActivity(intent); } } ``` But what if the activity that I'm being redirected to contains a gridview layout, how do I call that when I press the button? I don't have time to write my code here. It would be best if you just give me an idea or make a sample code thanks in advance.
2015/10/10
[ "https://Stackoverflow.com/questions/33050043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4054349/" ]
Your code should work on any Activity you have regardless of the layout they have. Just replace `Intent intent = new Intent(this, AnotherActivity.class);` with `Intent intent = new Intent(this, ActivitywithGridView.class);` Remeber that you cannot see a GridView if it is not populated with data.
23,565
I have created a trigger and am hopping for suggestions to clean up the trigger, making it more performant. **The reason for this trigger is:** The companies' website has a PHP insert, creating Contacts in Salesforce. However, it is possible that the contact already exists in Salesforce. (The current PHP module does not allow for external ids). My solution is to throw a specific error if the Contact email already exists. The error will contain the existing Contact ID. To throw this error I think a trigger is the best option, and this way a 'duplicate' Contact will not be created and I will be able to send the existing Contact's Id through the error. **The trigger is as follows:** ``` trigger trig_Contact_webToContact on Contact (before insert) { //Defining Variables String errorMsg = 'The email already exists on another Contact '; List<String>newEmail = new List<String>(); List<Id>newID = new List<String>(); List<Contact> newContacts = [SELECT id, email FROM Contact WHERE ID IN: Trigger.new]; for(Contact newContact:newContacts) //put emails and Ids in a list for use in SELECT { newEmail.add(newContact.email); newID.add(newContact.Id); } //List of Contacts that have the same email as inserted List<Contact> existingContacts = [SELECT id, email FROM Contact WHERE email IN: newEmail AND id NOT IN: newID]; if(existingContacts.size() > 0) { for(Contact ContactError:existingContacts) { for(Contact insertedContacts:newContacts) { if(ContactError.Email == insertedContacts.Email) { errorMsg += ContactError.Id; insertedContacts.addError(errorMsg); break; } } } } }//TRIGGER TRIG_CONTACT_WEBTOCONTACT ``` This trigger seems like it should work perfectly, but I feel I am repeating a few unnecessary steps. Any help on cleaning it up would be greatly appreciated.
2014/01/06
[ "https://salesforce.stackexchange.com/questions/23565", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/1182/" ]
I believe this should do the job (not tested it, though): ``` trigger trig_Contact_webToContact on Contact (before insert) { final String errMsg = 'The email already exists on another Contact: '; Set< String > emailSet = new Set< String >(); for( Contact c : Trigger.new ) emailSet.add( c.Email ); Map< String, Id > duplicateContactMap = new Map< String, Id >(); for( Contact c : [select Id, Email from Contact where Email = :emailSet] ) duplicateContactMap.put( c.Email, c.Id ); for( Contact c : Trigger.new ){ Id duplicateContactId = duplicateContactMap.get( c.Email ); if( duplicateContactId != null ) c.addError( errMsg + duplicateContactId ); } } ```
10,678,259
I'm trying to get Facebook to publish a read action using PHP. I've coded it totally wrong and need a little help: ``` <?php function curPageURL() { $pageURL = 'http'; if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";} $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } return $pageURL; } ?> <?php curl -F 'access_token=MY ACCESS TOKEN' \ -F 'article=echo 'echo curPageURL();' \ 'https://graph.facebook.com/me/news.reads' ?> ``` The second part is that bit I can't translate into PHP properly. I've no idea where to start as I'm a novice with PHP and only just learning the Open Graph API.
2012/05/21
[ "https://Stackoverflow.com/questions/10678259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1400839/" ]
Careful use of the `scanf` format string is needed. `%s` indicates a string that is delimited by a white space, in non technical terms, `scanf` will read characters until it finds a whitespace character such as a tab or space. This poses a problem for reading multiple words, this can be solved by using multiple `%s` in the format string, you must provide a seperate array for each word as an argument after the format string e.g. ``` scanf("%s%s%s", string1, string2, string3) ``` This `scanf` call expects three words from the user, where each word is delimited by a white space. Make sure there is allocated memory for each of arrays though otherwise you will write into memory the program does not own normally causing the program to crash. The exact same effect to the code above can be achieved by using `scanf` multiple times with a single `%s` in the format string. If you need everything as one string the same array you can use `strcat` which will concatenate two strings together. The function is simple to use, but once again make sure your arguments are allocated arrays before calling `strcat` otherwise it will likely cause a crash or unexpected behaviour. Here are references to both functions: `scanf` - <http://www.cplusplus.com/reference/clibrary/cstdio/scanf/> `strcat` - <http://www.cplusplus.com/reference/clibrary/cstring/strcat/> Hope this helps =]
34,511,940
I have a little problem with adding some HTML code using jQuery into a `td` element in an existing `table`. My HTML code is: ``` <table> <tbody> <tr> <td>Something</td> <td><strong>10</strong></td> </tr> </table> </tbody> ``` Now I have written this jQuery code to add a tooltip in the cell containing 'Something': ``` $('table tr').each(function(){ if ($(this).find('td').text() == 'Something') { $(this).html('<td><a class="tooltips" title="bla bla bla bla">Something</a></td>') } }); ``` In this case the jQuery function works correctly, I have added a tooltip to my `td` content, but the second `td` element is removed. I have tried using `.find('td:first')` but in any case the second `td` disappears. Can someone tell me how to write my jQuery code correctly so that the second `td` stays in the page? Thank you so much for help.
2015/12/29
[ "https://Stackoverflow.com/questions/34511940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2681462/" ]
The issue is because you're overwriting all the HTML within the `tr` element, not just replacing the first `td` containing the `Something` text value. Try this instead: ``` $('table td').each(function(){ if ($(this).text() == 'Something'){ $(this).replaceWith('<td><a class="tooltips" title="bla bla bla bla">Something</a></td>'); } }); ```
15,926
Some verbs have both a separable and an inseparable form, like [durchlaufen](http://dictionary.reverso.net/german-english/durchlaufen). In case of "durchlaufen", the **separable** form is mainly **intransitive**, while the **inseparable** form is mainly **transitive** (although the separable form also has a transitive meaning.) In general, is there any rule of thumb for these verbs on when (that is, for which meaning) they are separable and when they are not? Or do we simply have to memorize/get used to it?
2014/09/27
[ "https://german.stackexchange.com/questions/15926", "https://german.stackexchange.com", "https://german.stackexchange.com/users/5478/" ]
First of all, as it shown in [the link given by rogermue](https://www.deutschplus.net/pages/153) or at [this page by canoonet.eu](http://canoonet.eu/services/WordformationRules/Derivation/To-V/V-To-V/Praefig.html), possible candidates for such verbs can be made out by their prefix: Only *durch, über, um, unter, wider* and *wieder* can lead to verbs that are both separable and inseparable. Note that both sources list *wieder* as an always-separable prefix, which is wrong by counter-example: [*wiederholen*](https://www.duden.de/rechtschreibung/wiederholen_zurueckholen_holen) (separable, *to bring back*) and [*wiederholen*](https://www.duden.de/rechtschreibung/wiederholen_bekraeftigen_proben) (inseparable, *to repeat*). Second, as they also point out there, separable verbs have the stress on the prefix, while inseparable verbs have an unstressed prefix. So (first rule, no need for a thumb): Memorize how to pronounce these verbs in their different meaning, and you get the sep./insep. distinction for granted. Something more closer to a rule of thumb, less need for memorizing: Estimate which part of the verb is more important for the composed meaning. That’s the part that is stressed, and then again you also know whether it’s a separable verb or not. Some examples (don’t take my attempts of explanation too literally, please) > > ***durch**laufen* (separable) – It runs, yes; but it runs **through**. > > *durch**laufen*** (inseparable) – They **run** and run and run, and eventually their are through. > > > ***um**schreiben* (separable) – It’s writing with the purpose of **changing** something (*um* signifies some sort of change here) > > *um**schreiben*** (inseparable) – Very similar to the always inseparable *beschreiben:* The action is in the focus, and *um* qualifies it as *going around* (compare with *to circumscribe*) looking from different angles to get the picture. > > > ***um**fahren* (separable) – Something went **down**, and it is this result that matters. That this was reached by some driving activity is secondary. > > *um**fahren*** (inseparable) – Again, the action of driving is in the focus, and *um* is used to qualify it as *going around.* > > > As for transitive vs. intransitive - I don't think that this is of great help here. E.g. both versions of *umfahren* are transitive, and you will likely find examples for all four possible combinations of separable/inseparable with transitive/intransitive.
5,290,525
is there a way to disable all fields (textarea/textfield/option/input/checkbox/submit etc) in a form by telling only the parent div name in jquery/javascript?
2011/03/13
[ "https://Stackoverflow.com/questions/5290525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578449/" ]
Try using the [`:input`](http://api.jquery.com/input-selector/) selector, along with a parent selector: ``` $("#parent-selector :input").attr("disabled", true); ```
63,937
I'm having some problems installing [Symantec AntiVirus Corporate Edition 10.2 for Windows Vista](http://service1.symantec.com/SUPPORT/ent-security.nsf/docid/2006102615175748). My client requires this exact version. The system on which I'm installing the software is recently purchased system (i.e. relatively "clean") that came with [Symantec Norton Internet Security 2009](http://www.symantec.com/norton/internet-security) preinstalled. The system has a 64-bit AMD Athlon and it is running Microsoft Windows Vista 64 Home Premium Edition (again, preinstalled). My plan was to uninstall the 2009 version and install the 10.2 corporate edition. For my first attempt, I ran the Norton uninstall program that I found in the Norton folder. The uninstall program seemed to work properly. Next, I ran the corporate 10.2 installer, but I got an error dialog saying: ``` Symantec Antivirus install FAILED! Please reboot and try again. note: You may need to run NONAV249.exe if the reinstall fails ``` [![](https://i.stack.imgur.com/mZON9.png)](https://i.stack.imgur.com/mZON9.png) (source: [iparelan.com](http://iparelan.com/NortonError.png)) Suspecting that the 2009 uninstall wasn't clean, I ran the [Norton Removal Tool](http://service1.symantec.com/Support/tsgeninfo.nsf/docid/2005033108162039). Then I tried to install the corporate 10.2 version again, but I got the exact same error. I'm pretty sure that my system meets the [system requirements](http://service1.symantec.com/support/ent-security.nsf/docid/2006103013172348) for Corporate Edition 10.2. It seems that at least [one other person](http://www.symantec.com/connect/forums/unable-install-corporate-edition-sav102) has had this same problem. **Any thoughts on how to complete this installation of Corporate Edition 10.2? What is `NONAV249.exe`?**
2009/09/09
[ "https://serverfault.com/questions/63937", "https://serverfault.com", "https://serverfault.com/users/1438/" ]
Do you have the client install package for Vista? If I remember correctly from about a year ago, I had to specify the client install location and point it to where the Vista client was. I don't remember if I had to download it separately, but I believe I did.
23,264,679
Title pretty much explains it all. Inputting ngSwipeLeft="someFunction()" does not seem to work as I hoped it would. Maybe I am doing it wrong, but what are your ideas? [Here](https://docs.angularjs.org/api/ngTouch/directive/ngSwipeLeft) is the documentation for ngSwipeLeft. [Example](http://plnkr.co/edit/eaSCqNzu5TRcT0lPE5lv?p=preview) Thanks, Ben
2014/04/24
[ "https://Stackoverflow.com/questions/23264679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3286707/" ]
I think what you need to do is create a controller for that javascript, and then work off of its scope. ``` <div ng-show="!showActions" data-ng-swipe-left="someFunction()"> Some list content, like an email in the inbox </div> <div ng-show="showActions" data-ng-swipe-right="someFunction()">"> <button ng-click="reply()">Reply</button> <button ng-click="delete()">Delete</button> </div> ``` And the JS ``` $scope.showActions = false; $scope.someFunction = function () { $scope.showActions = !$scope.showActions; }; ``` That is how I do it in my applications. I hope it helps. Here is the [Plunk](http://plnkr.co/edit/d5VyDWcHul6aKPvRYMk1?p=preview). The plunk works but it is a little off. It sometimes highlights instead of switching over. It works best when swiping to the right side.
71,189,989
I have a class named stock, and I am trying to concatenate quarterly earnings for an object. ``` class Stock : def __init__(self,name,report_date,earning,estimate): self.Name = name self.Report_date = report_date self.Earning = [earning] self.Estimate = estimate def list_append(self,earning): self.Earning = [self.Earning,earning] example = Stock('L',2001,10,10) example.list_append(11) example.list_append(12) example.list_append(13) ``` Like this. So that finally i want the output of example.Earning = [10,11,12,13]. But the output is coming out as example.Earning = [[[[10], 11], 12],13] I tried the following. ``` self.Earning = (self.Earning).append(earning) Error = "int" does not have attribute append ``` and ``` self.Earning[-1:] = earning ``` But they are throwing me errors. How can I get rid of this embedded list([[[10], 11], 12]) and make just one list([10,11,12,13])?
2022/02/19
[ "https://Stackoverflow.com/questions/71189989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17834500/" ]
To solve your problem and get rid of the embedded lists, you can do: ``` def list_append(self,earning): self.Earning = [*self.Earning,earning] ``` The \* will spread the old list `self.Earnings` and adds `earning` to a new list and assign it to self.Earning Or just simply use method `append`: ``` def list_append(self,earning): self.Earning.append(earning) ```
16,526,617
Write a Prolog program to print out a square of n\*n given characters on the screen. Call your predicate square/2. The first argument should be a (positive) integer. the second argument the character (any Prolog term) to be printed. Example: ``` ?-square(5, '*'). ***** ***** ***** ***** ***** Yes ``` I just start to learn this language. I did this: ``` square(_,'_'). square(N, 'B') :- N>0, write(N*'B'). ``` It doesn't work at all. Can anyone help me?
2013/05/13
[ "https://Stackoverflow.com/questions/16526617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2378457/" ]
So your question is, basically, "how do I write a loop nested in a loop?" This is how you write an empty loop with an integer for a counter: ``` loop(0). loop(N) :- N > 0, N0 is N-1, loop(N0). ``` which in C would be: ``` for(i=0; i < n; ++i) { } ``` And you seem to know already how to print (`write(foo)`).
652,810
A company is proposing a pumped hydro system where they state on their website as “capable of producing up to 335 MW of electricity with around 8 hours storage”. The same company is proposing a battery proposal that is stated on website as “with capacity to dispatch up to 500 MW of power over a duration of up to 4 hours”. 1. So does this mean the PH is producing less total power than the battery? 2. If we add in the time factor does this mean to get MWh you simply divide the total storage by the number of hours that it produces for? This is very confusing to novices trying to work out the better option.
2023/02/04
[ "https://electronics.stackexchange.com/questions/652810", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/332139/" ]
This question is about the relationship between energy and power. ----------------------------------------------------------------- The SI unit of energy is the joule (J). Power is the rate of energy transfer. The SI unit of power is the watt (W). One watt = one joule per second. Whilst the SI unit of energy is the joule, a common measure is the watt-hour (Wh.) This is the energy transferred by one watt for one hour, so equivalent to 3600 J. With this background, we can see that the storage capacity of a system comes from power \* duration, but we need to exercise care because sometimes we see peak power quoted with the duration quoted for a lower average power. Q1. "Total Power" doesn't really make sense in this context. "Power" is a measure of energy transfer/consumption rate. The PH system can deliver 335 MW, whilst the battery system 500 MW. So the battery system can deliver almost 50% more power. Q2. Assuming the power quoted can be sustained for the full duration, we can see the PH system has a capacity of 335 MW x 8 h=2680 MWh, whilst the battery system has a capacity of 500 MW x 4 hr=2000 MWh. So the PH system has around 25% more energy storage.
12,698,376
I have a table. I have 2 variables, one is a `bit`, the other is an `int`. Table: `WorkGroupCollectionDetail` Variables: `@WorkgroupID int, @IsFSBP bit` The table has `WorkGroupId int PK` and `WorkGroupCollectionCode varchar PK`. That's it. I can run a query like this: ``` SELECT WorkGroupId FROM WorkGroupCollectionDetail WHERE WorkGroupCollectionCode = 'FSBP' ``` and it gives me a list of `WorkGroupID`. So what I need to do is if the value of `@WorkgroupID` is inside the results of that query, I need to set the bit variable to true.
2012/10/02
[ "https://Stackoverflow.com/questions/12698376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` select @IsFBSP = case when exists ( select 42 from WorkGroupDetailCollection where WorkGroupCollectionCode = 'FSBP' and WorkGroupId = @WorkGroupId ) then 1 else 0 end ``` which is logically equivalent to: ``` select @IsFBSP = case when @WorkGroupId in ( select WorkGroupId from WorkGroupDetailCollection where WorkGroupCollectionCode = 'FSBP' ) then 1 else 0 end ``` A query using `EXISTS` often performs better than a query using `IN`. You can check the execution plans to see how they compare in your particular case. Note that these examples include setting the bit value to zero as well as one.
9,163,224
I need help with a js/jQuery automat form calculator. The function is `time=games*(players*15)`, so basically there are 3 form fields `games` `players` result in field `time`. I want the result to be in real time not by pressing a button. Here is the code I made with a trigger button, but I want without calculate button, just by completing fields. Nvm, I resolved it with an `onChance` for fields. ``` <SCRIPT LANGUAGE="JavaScript"> function CalculateSum(games, players, form) { var A = parseFloat(games); var B = parseFloat(players); form.Time.value = A*(B*15) ; } function ClearForm(form)s { form.input_A.value = ""; form.input_B.value = ""; form.Time.value = ""; } // end of JavaScript functions --> </SCRIPT> // HTML --> <FORM NAME="Calculator" METHOD="post"> <P>Games: <INPUT TYPE=TEXT NAME="input_A" SIZE=10></P> <P>Plyers <INPUT TYPE=TEXT NAME="input_B" SIZE=10></P> <P><INPUT TYPE="button" VALUE="Calculate time" name="Calculate time" onClick="CalculateSum(this.form.input_A.value, this.form.input_B.value, this.form)"></P> <P><INPUT TYPE="button" VALUE="Clear" name="Clear" onClick="ClearForm(this.form)"></P> <P>Time = <INPUT TYPE=TEXT NAME="Time" SIZE=12></P> </FORM> ```
2012/02/06
[ "https://Stackoverflow.com/questions/9163224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1192145/" ]
You have run into [endianness](http://en.wikipedia.org/wiki/Endianness). IP packets have all fields in network byte order (aka "big-endian"), and your host system probably runs little-endian. Look into `ntohs()` and friends for one approach. The proper approach is to not copy the structure as-is from the network data, but instead extract each field manually and byte-swap it if necessary. This also works around any issues with padding and alignment, there's no guarantee that your `struct` is mapped into your computer's memory in exactly the same way as the packet is serialized. So you would do e.g.: ``` udp_header.sport = ntohs(*(unsigned short*) (packet + 14 + 4 * ip_hdr->ip_hl)); ``` This is also a bit iffy, since it assumes the resulting address can validly be cast into a pointer to `unsigned short`. On x86 that will work, but it's not epic. Even better, in my opinion, is to drop the use of pointers and instead write a function called e.g. `unsigned short read_u16(void *packet, size_t offset)` that extracts the value byte-by-byte and returns it. Then you'd just do: ``` udp_header.sport = read_u16(packet, 14 + 4 * ip_hdr->ip_hl); ```
35,955,409
How would I calculate the median (use the median function) of each row by using the FOR loop. Using a matrix; mat = matrix(rnorm(100), 5) Thank you in advance. -Bill
2016/03/12
[ "https://Stackoverflow.com/questions/35955409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5998309/" ]
Here is one possible solution: ``` mat = matrix(rnorm(100), 5) medians_of_mat <- numeric() for(i in 1:nrow(mat)) { medians_of_mat[i] <- median(mat[i, ]) } ``` An easier way would be to use apply: ``` apply(mat, 1, median) ```
2,036,096
In the following rules for the case when array decays to pointer: > > An lvalue [see question 2.5] of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element; the type of the resultant pointer is pointer-to-T. > > > (The exceptions are when the array is the operand of a sizeof or & operator, or is a literal string initializer for a character array.) > > > How to understand the case when the array is "literal string initializer for a character array"? Some example please. Thanks!
2010/01/10
[ "https://Stackoverflow.com/questions/2036096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/156458/" ]
The three exceptions where an array does not decay into a pointer are the following: **Exception 1.** — When the array is the operand of `sizeof`. ``` int main() { int a[10]; printf("%zu", sizeof(a)); /* prints 10 * sizeof(int) */ int* p = a; printf("%zu", sizeof(p)); /* prints sizeof(int*) */ } ``` **Exception 2.** — When the array is the operand of the `&` operator. ``` int main() { int a[10]; printf("%p", (void*)(&a)); /* prints the array's address */ int* p = a; printf("%p", (void*)(&p)); /*prints the pointer's address */ } ``` **Exception 3.** — When the array is initialized with a literal string. ``` int main() { char a[] = "Hello world"; /* the literal string is copied into a local array which is destroyed after that array goes out of scope */ char* p = "Hello world"; /* the literal string is copied in the read-only section of memory (any attempt to modify it is an undefined behavior) */ } ```
55,514,434
I came across this basic question, where switch case is used with string. Break statement is not used between cases but why it going to all the cases even when it is not matching the case string? So I'm curious to know **why is the output 3 and not 1?** ``` public static void main(String [] args) { int wd=0; String days[]={"sun","mon","wed","sat"}; for(String s:days) { switch (s) { case "sat": case "sun": wd-=1; break; case "mon": wd++; case "wed": wd+=2; } } System.out.println(wd); } ```
2019/04/04
[ "https://Stackoverflow.com/questions/55514434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7758110/" ]
You don't have a `break;` at the end of `case "mon"` so value is also incremented by 2 which you didn't expect, flow: ``` 0 -1 -1 +1+2 +2 = 3 ^ ^ ^ ^ ^ init sat sun mon wed ``` Adding a break as below will result with output 1 ``` case "mon": wd++; break; ```
43,654,107
I have a system that I can output a spreadsheet from. I then take this outputted spreadsheet and import it into MS Access. There, I run some basic update queries before merging the final result into a SharePoint 2013 Linked List. The spreadsheet I output has an unfortunate Long Text field which has some comments in it, which are vital. On the system that hosts the spreadsheet, these comments are nicely formatted. When the spreadsheet it output though, the field turns into a long, very unpretty string like so: > > 09:00 on 01/03/2017, Firstname Surname. :- Have responded to request for more information. 15:12 on 15/02/2017, Firstname Surname. :- Need more information to progress request. 17:09 on 09/02/2017, Firstname Surname. :- Have placed request. > > > What I would like to do is run a query (either in MS Access or MS Excel) which can scan this field, detect occurrences of "##:## on ##/##/####, Firstname Surname. :-" and then automatically insert a line break before them, so this text is more neatly formatted. It would obviously skip the first occurrence of this format, as otherwise it would enter a new line at the start of the field. Ideal end result would be: > > 09:00 on 01/03/2017, Firstname Surname. :- Have responded to request > for more information. > > 15:12 on 15/02/2017, Firstname Surname. :- Need more information to progress request. > > 17:09 on 09/02/2017, Firstname Surname. :- Have placed request. > > > To be honest, I haven't tried much myself so far, as I really don't know where to start. I don't know if this can be done without regular expressions, or within a simple query versus VBA code. I did start building a regular expression, like so: ``` [0-9]{2}:[0-9]{2}\s[o][n]\s[0-9]{2}\/[0-9]{2}\/[0-9]{4}\,\s ``` But this looks a little ridiculous and I'm fairly certain I'm going about it in a very unnecessary way. From what I can see from the text, detecting the next occurrence of "##:## on ##/##/####" should be enough. If I take a new line after this, that will suffice.
2017/04/27
[ "https://Stackoverflow.com/questions/43654107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7930309/" ]
This is the expected behaviour as per <https://github.com/angular/angular.js/issues/14027> *Since you are using interpolation ({{...}}). $interpolate must return a string and thus tries to stringify non-string values, by converting them to JSON.*
36,009
It was pretty exciting to borrow my dad's old Nikon 55mm f/2.8 AI-s and try it on my Nikon D3200. I have to use it in full manual mode, but it gets great results! Amazing how a lens designed in 1979 still works on the new cameras. However, I was wondering why the camera does not allow me to control the aperture from the camera itself. I can see that the lens has an aperture control ring, which looks similar to the modern lenses I have. I also notice that there is a pin around 8 o'clock on the mount that gets depressed with the AI-s lens but stays free when using a modern lens. It feels as if Nikon intentionally designed the D3200 to not do aperture control on this camera for AI-s lenses even though it may have the capability to do so. Is that a correct assumption? If yes, then I was just curious, why would they want to do that?
2013/03/21
[ "https://photo.stackexchange.com/questions/36009", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/13610/" ]
Yes, **the D3200** (like all current low end Nikon DSLRs) **can't control non-electronic lenses.** The meter (and viewfinder) are illuminated at the maximum possible aperture and calculating exposure would require knowing the difference between it and the selected aperture: hence the ability of higher end cameras to implement A and assisted M modes thanks to the use of a [relative aperture sensor, as visible in this image](http://static.photo.net/attachments/bboard/00a/00apNV-496795684.jpg) The opposite problem is readily solvable on AI-S (and derived) lenses given the [proportionality between the stopdown lever and the resulting aperture](http://www.throughthefmount.com/articles_back_difference_ai_ais.html#tabellelinks), to the extent that some film cameras predating on-camera aperture control can fully use G-series lenses in the P and S modes! This still requires knowledge of the minimum aperture (as implemented by mechanical sensors on those cameras), and the higher end digital bodies have exactly a menu feature for programming older lenses but without getting in-camera aperture control. *How much of it is due to intentional marketing restrictions is up to personal preference.* **If you're really inclined, [some companies](http://www.naturfotograf.com/lens_CPUconversion.html) will add electronics to almost any lens imaginable**.
1,692,697
Show that > > A Normed Linear Space $X$ is a Banach Space iff every absolutely convergent series is convergent. > > > **My try**: Let $X$ is a Banach Space .Let $\sum x\_n$ be an absolutely convergent series .Consider $s\_n=\sum\_{i=1}^nx\_i$. Now $\sum \|x\_n\|<\infty \implies \exists N$ such that $\sum\_{i=N}^ \infty \|x\_i\|<\epsilon$ for any $\epsilon>0$ Then $\|s\_n-s\_m\|\le \sum \_{i=m+1}^n \|x\_i\|<\epsilon \forall n,m>N$ So $s\_n$ is Cauchy in $X$ and hence converges $s\_n\to s$ (say). Thus $\sum x\_i$ converges. Conversely, let $x\_n$ be a Cauchy Sequence in $X$. Here I can't proceed how to use the given fact. Any help will be great.
2016/03/11
[ "https://math.stackexchange.com/questions/1692697", "https://math.stackexchange.com", "https://math.stackexchange.com/users/294365/" ]
For the converse argument; let $X$ be a normed linear space in which every absolutely convergent series converges, and suppose that $\{x\_n\}$ is a Cauchy sequence. For each $k \in \mathbb{N}$, choose $n\_k$ such that $||(x\_m − x\_n)|| < 2^{−k}$ for $m, n \geq n\_k$. In particular, $||x\_{n\_{k+1}}−x\_{n\_k}||< 2^{-k}$. If we define $y\_{1} = x\_{n\_{1}}$ and $y\_{k+1} = x\_{n\_{k+1}} − x\_{n\_{k}}$ for $k \geq 1$, it follows that $\sum ||y\_{n}|| ≤ ||x\_{n\_{1}} || + 1$ i. e., ($y\_{n}$) is absolutely convergent, and hence convergent.
60,512,711
I am trying to calculate the time difference in java by input time format in 12 hours it works well when i input start time `11:58:10 pm` and end time `12:02:15 am`. But as i enter 12:00:00 am and 12:00:00 pm it give difference 0 minutes. don't know why. Below is my code please let me know where i am wrong. ``` Scanner input = new Scanner(System.in); System.out.print("Enter start time (HH:mm:ss aa): "); String starttime = input.nextLine(); System.out.print("Enter end time (HH:mm:ss aa): "); String endtime = input.nextLine(); //HH converts hour in 24 hours format (0-23), day calculation SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss aa"); Date d1 = null; Date d2 = null; try { d1 = format.parse(starttime); d2 = format.parse(endtime); //in milliseconds long diff = d2.getTime() - d1.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; System.out.print(diffMinutes + " minutes and "+diffSeconds + " seconds."); } catch (Exception e) { System.out.println("Invalid fromat"); } ```
2020/03/03
[ "https://Stackoverflow.com/questions/60512711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3828909/" ]
The new `java.time` methods `LocalTime`, `DateTimeFormatter` and `Duration` provide much better methods for handling this. For example: ``` DateTimeFormatter format = DateTimeFormatter.ofPattern("h:m:s a"); LocalTime time1 = LocalTime.parse("12:00:00 am", format); LocalTime time2 = LocalTime.parse("2:00:20 pm", format); Duration dur = Duration.between(time1, time2); System.out.println(dur.toMinutes() + " minutes " + dur.toSecondsPart() + " seconds"); ``` Note: `Duration.toSecondsPart` requires Java 9 or later, the rest of this code requires Java 8 or later.
1,369
I have been vocal in several early discussions about the need to gently redirect the enthusiasm of first time posters rather than sharply remind them that their contribution is inappropriate. I fear that my liberal attitudes have now been demonstrated to have failed miserably. A new user posted a question (now titled) [What criteria should I look for to publish my cemetery records online?](https://genealogy.stackexchange.com/questions/2384) which self-evidently failed to meet the criteria of a good SE question when it asks for "the best ...". I commented with a warm fuzzy welcome and a gentle suggestion of how the question might be improved. Predictably, the question has attracted a number of short answers that together constitute a list of options and personal preferences. The OP clearly sees no need to amend the body of the question because the community has given him the answer he was wanting. More seriously, the question that I probably should have voted to close (as "not a question") has now earned a **Nice Question** badge through upvoting. What is the appropriate middle way that will encourage new or inexperienced users to continue to visit and contribute without leaving open the possibility that their less-than-desirable first efforts will be seen as the norm?
2012/12/03
[ "https://genealogy.meta.stackexchange.com/questions/1369", "https://genealogy.meta.stackexchange.com", "https://genealogy.meta.stackexchange.com/users/70/" ]
I don't think your initial comment could have been improved upon -- it struck the right welcoming tone but pointed out the problems. However, the OP has edited the question title and is editing the body. I made another gentle suggestion how to change it and why, and they responded and edited it again immediately. Now, I think it's looking OK. On this important and more general point: > > What is the appropriate middle way that will encourage new or inexperienced users to continue to visit and contribute without leaving open the possibility that their less-than-desirable first efforts will be seen as the norm? > > > it may be that we need to be a little **less** wary of editing questions that need improving on behalf of the OP, always telling them what we've done and why and inviting them to rollback if they're unhappy, rather than hoping they'll do the edit themselves. If the comment we make is just as warm and fuzzy and encouraging, it should still have the desired effect.
26,695,072
I'm experimenting with the news themes tonight and I'm wondering if anyone knows these fix to this issue. This appears on the stock [Toolbar](https://developer.android.com/reference/android/support/v7/widget/Toolbar.html "API Reference: Toolbar") and even, as seen below, when referring to custom layout file. It's relatively minor but my OCD eyes go right to it so maybe someone can help. Thanks :) ![Screenshot of cropped subtitle descenders.](https://i.stack.imgur.com/KYZW4.png)
2014/11/02
[ "https://Stackoverflow.com/questions/26695072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/562146/" ]
**UPDATE**: Inheriting from the correct theme and declaring attributes in pairs (with and without the `android:` prefix) was the fix! ``` <!-- Base app theme. --> <style name="AppTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="android:actionBarStyle">@style/MyActionBar</item> <item name="actionBarStyle">@style/MyActionBar</item> </style> <!-- ActionBar styles. --> <style name="MyActionBar" parent="Widget.AppCompat.ActionBar"> <item name="android:titleTextStyle">@style/MyActionBarTitleText</item> <item name="titleTextStyle">@style/MyActionBarTitleText</item> <item name="android:subtitleTextStyle">@style/MyActionBarSubTitleText</item> <item name="subtitleTextStyle">@style/MyActionBarSubTitleText</item> <item name="android:background">@color/blue</item> <item name="background">@color/blue</item> </style> <style name="MyActionBarTitleText" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"> <item name="android:textColor">@color/white</item> </style> <style name="MyActionBarSubTitleText" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Subtitle"> <item name="android:textColor">@color/white</item> <item name="android:textSize">@dimen/subtitle</item> </style> ```
17,344,182
I am new to junit and mockito, so the problem might be an obvious one. I have an issue with mockito where a locally instantiated object within the 'test object' is null. There are no private / protected / final methods being called in this particular section, so that is not the issue. Also I am using PowerMockito for other private method calls. section of my class to test: null pointer exception being thrown on user.getId() - last line here: ``` SupportProdUpdatesImpl pAdd = new SupportProdUpdatesImpl(); Add.setQueryProcssStatus(form.getQueryProcssStatus()); pAdd.setQueryTitle(form.getQueryTitle().toUpperCase()); pAdd.setQueryType(form.getQueryType().toUpperCase()); logger.debug("*** query String = " + form.getQuerySQL() ); pAdd.setQuerySQL(StringUtils.trim(form.getQuerySQL())); pAdd.setMakerId(user.getId()); ``` In my test i have created a ``` User user = mock(User.class) // interface of user when(user.getId()).thenReturn(new Integer(111))); ``` I do not understand what i am doing wrong.. Any help would be appreciated! thanks
2013/06/27
[ "https://Stackoverflow.com/questions/17344182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359079/" ]
I believe what is going on is that you have not provided the `user` mock to the class under test.
62,892,628
Ok I have read so much about NSArray NSDictionary I'm lost now, what I want is to print the value 'name' from the first array item of my custom plist. This is my plist: [![enter image description here](https://i.stack.imgur.com/txpZ2.png)](https://i.stack.imgur.com/txpZ2.png) and this is my code in my ViewController.swift: ``` class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let path = Bundle.main.path(forResource: "test", ofType: "plist") let dic = NSArray(contentsOfFile: path!) print(dic?.firstObject) } } ``` in my console I see: ``` Optional({ active = 0; name = "John Doe"; }) ``` I would think that `print(dic?.firstObject["name"])` would do the trick but I get an error: *Value of type 'Any?' has no subscripts* So how do I print the values of **name** and **active** of my first array? I know there are lots of answers on SO regarding this question, that's the reason I got so far. but I just don't know how to fix this. Kind regards, Ralph
2020/07/14
[ "https://Stackoverflow.com/questions/62892628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2603640/" ]
First of all please **never** use the `NSArray/NSDictionary` related API in Swift to read a property list. You are throwing away the type information. However you can read the values with ``` let array = NSArray(contentsOfFile: path!) as! [[String:Any]] for item in array { let name = item["name"] as! String let active = item["active"] as! Bool print(name, active) } ``` The dedicated and recommended API is `PropertyListSerialization` : ``` let url = Bundle.main.url(forResource: "test", withExtension: "plist")! let data = try! Data(contentsOf: url) let array = try! PropertyListSerialization.propertyList(from: data, format: nil) as! [[String:Any]] ``` A better way is the `Codable` protocol and `PropertyListDecoder` ``` struct User : Decodable { let name : String let active : Bool } override func viewDidLoad() { super.viewDidLoad() let url = Bundle.main.url(forResource: "test", withExtension: "plist")! let data = try! Data(contentsOf: url) let array = try! PropertyListDecoder().decode([User].self, from: data) for item in array { print(item.name, item.active) } } ``` The code must not crash. If it does you made a design mistake
51,580,562
my problem is that one row added successfully but when adding more data it shows an error given below. there is duplicate entry but i want to insert two laptop data for the same student. Im beginner in hibernate please guide me sir. ``` Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190) at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3587) at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:103) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:453) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:345) at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350) at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56) at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1218) at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:421) at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101) at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177) at HibRelation.App.main(App.java:43) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY' at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) at com.mysql.jdbc.Util.getInstance(Util.java:386) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1040) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2794) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187) ... 13 more ``` this is my student.java class ``` package HibRelation; import java.util.*; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.OneToOne; @Entity public class Student { @Id private int RollName; private String Lname; private int marks; @OneToMany(mappedBy = "std") private List<Laptop> laptop = new ArrayList<Laptop>(); public int getRollName() { return RollName; } public void setRollName(int RollName) { this.RollName = RollName; } public String getLname() { return Lname; } public void setLname(String Lname) { this.Lname = Lname; } public int getMarks() { return marks; } public void setMarks(int marks) { this.marks = marks; } public List<Laptop> getLaptop() { return laptop; } public void setLaptop(List<Laptop> laptop) { this.laptop = laptop; } @Override public String toString() { return "Student{" + "RollName=" + RollName + ", Lname=" + Lname + ", marks=" + marks + '}'; } } ``` and this is my Laptop.java class ``` import java.util.*; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; @Entity public class Laptop { @Id private int id; private String lname; @ManyToOne private Student std; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public Student getStd() { return std; } public void setStd(Student std) { this.std = std; } } ``` and this is main logic App.java ``` public class App { public static void main(String[] args) { Student student=new Student(); student.setRollName(102); student.setLname("Dinu"); student.setMarks(95); Laptop lap= new Laptop(); lap.setId(1); lap.setLname("hp"); student.getLaptop().add(lap); lap.setStd(student); Configuration con=new Configuration().configure().addAnnotatedClass(Student.class).addAnnotatedClass(Laptop.class); StandardServiceRegistry registry=new StandardServiceRegistryBuilder().applySettings(con.getProperties()).build(); SessionFactory sfact=con.buildSessionFactory(registry); Session session = sfact.openSession(); session.beginTransaction(); session.save(student); session.save(lap); session.getTransaction().commit(); } } ``` Configuration.cfg.xml ```html <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedata</property> <property name="hibernate.connection.username">root</property> <property name="hbm2ddl.auto">update</property> <property name="show_sql">true</property> </session-factory> </hibernate-configuration> ```
2018/07/29
[ "https://Stackoverflow.com/questions/51580562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10151294/" ]
The error is caused by the duplication of a primary key in laptop table. A primary key is a column which uniquely identifies any row of the table. if you want to insert more than once keep changing the id value of laptop.So when you run the program for next time change the value of Id. Like ``` laptop.setId(2); //or something else which is not present in the table already ``` if you want to add the same laptop into a new student then retrieve that laptop first for e.g ``` Laptop theLaptop = Session.get(Laptop.class,theId) // theId is the laptopid student.addLaptop(theLaptop); session.save(student); ```
194,707
At least two other GMs and I will be running a shared game that uses the optional firearms from the DMG (pg 269). Renaissance arms will be available, and we will be deciding whether we will also make modern arms available. The game will start at level 2, and we currently expect it to reach level 20. **My question is, how competitive will melee martial characters be, compared to ranged firearm users?** As I understand it, ranged attackers normally have less DPR but benefit from additional range. Do ranged firearm users outshine melee martial characters in damage? Do they start as competitive but fall off at later levels? Is the increase from firearm damage offset by the increased cost of ammunition or feats? All players who intend to make a ranged character already plan on picking up firearms proficiency. Knowing this can inform how we award firearms proficiency and determine the costs and availability of different firearms. I'm looking for answers based on experience running or playing in games where firearms were available.
2021/12/19
[ "https://rpg.stackexchange.com/questions/194707", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/73602/" ]
Varies ------ Renaissance Firearms are competitive with crossbows (higher damage compared to longer range), before introducing Crossbow Expert. Crossbow Expert relegates renaissance firearms to gimmicks. Melee characters are highly competitive, often dominant, compared to crossbows or these firearms. A Musket deals 1d12 + Dex damage (average 6.5 + Dex) once per round; a Greatsword deals 2d6 + Str damage (average 7 + Str) with *each* successful attack. That's a huge difference that makes muskets (and pistols) *uninteresting* for characters with **Extra Attack**. So uninteresting that **ranged combatants** will prefer bows and crossbows over firearms. I played a ranged Fighter in an early 5e game; the DM was excited to have a gun-using hunter, and by level 6 I was using a scavenged longbow as my primary weapon - only the introduction of a home brew repeating firearm^ got that character to use firearms again. Modern Firearms are a completely different beast. I was looking at a home campaign and wanted to play test the modern firearms; I discovered that they were the best martial weapons in existence. The basic pistol does 2d6 damage (greatsword levels); the shotgun, revolver, and automatic rifle do 2d8 damage (like a War Cleric with Divine Strike); the hunting rifle does 2d10 damage (like *Eldritch Blast* at level 5); all + Dex because they are ranged weapon attacks. That's average 7 / 9 / 11 + Dex damage per attack. And the **Burst Fire** ability lets the weapon deal AoE damage, slaughtering swarms. Introducing Modern Firearms is the death of melee combat as a *primary combat style*. It is still a viable tactical choice, and for certain classes and builds it is the superior choice, but every competitive Fighter will choose a Ranged combat style and avoid melee-only class options (like Battle Master). ^The weapon dealt 3d8 damage, had Ammunition 6, had Range 120/500, and was magical. It was stupidly powerful as a base weapon. --- While not a primary question, this statement needs to be addressed: > > As I understand it, ranged attackers normally have less DPR but benefit from additional range. > > > The DPR for range attackers is generally the same as melee combatants. The massive +2 attack bonus from the Ranged Combat Style, uniformly d6/d8 weapon dice, ability to add their primary stat to damage, and access to the Marksman feat allows ranged weapon Damage Per Round to be about the same as melee weapon combat (lower damage per hit is offset by a 10% higher hit chance). The most noteworthy drawback of ranged weapon attacks is a long list of incompatible class abilities.
3,544,652
I'm trying to write a simple console app that dumps the contents of HKLM to the console. The output should look something like: ``` HKEY_LOCAL_MACHINE HKEY_LOCAL_MACHINE\BCD00000000 HKEY_LOCAL_MACHINE\BCD00000000\Description KeyName: BCD00000000 System: 1 TreatAsSystem: 1 GuidCache: System.Byte[] HKEY_LOCAL_MACHINE\BCD00000000\Objects HKEY_LOCAL_MACHINE\BCD00000000\Objects\{0ce4991b-e6b3-4b16-b23c-5e0d9250e5d9} HKEY_LOCAL_MACHINE\BCD00000000\Objects\{0ce4991b-e6b3-4b16-b23c-5e0d9250e5d9}\Description Type: 537919488 HKEY_LOCAL_MACHINE\BCD00000000\Objects\{0ce4991b-e6b3-4b16-b23c-5e0d9250e5d9}\Elements HKEY_LOCAL_MACHINE\BCD00000000\Objects\{0ce4991b-e6b3-4b16-b23c-5e0d9250e5d9}\Elements\16000020 Element: System.Byte[] ``` I haven't had much luck researching how to do this. Any help would be greatly appreciated.
2010/08/23
[ "https://Stackoverflow.com/questions/3544652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/386772/" ]
You know there's already an app that dumps registry contents, right? ``` REG EXPORT HKLM hklm.reg ``` Fun part is, it exports the keys in a text format, but that text file can be imported using either REG or the registry editor.
53,251,540
I have a code in which I need to find the number of `li` tags, not the nested ones. ``` <ul class="ulStart"> <li> <ul class="ulNested"> <li></li> <li></li> </ul> </li> <li></li> </ul> ``` Doing ``` document.querySelector('.ulStart').getElementsByTagName('li') ``` Gives me 4 `<li>`, which is not what I want, I want the number of `li` tags present in `ulStart`. Let me know if there is any way to do so. No jQuery, pure javascript.
2018/11/11
[ "https://Stackoverflow.com/questions/53251540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4453053/" ]
```js let count = document.querySelectorAll("ul.ulStart > li").length; console.log(count); ``` ```html <ul class="ulStart"> <li> <ul class="ulNested"> <li></li> <li></li> </ul> </li> <li></li> </ul> ``` Use the `>` (direct child) CSS selector. See [MDN - Child selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_selectors).
33,152,220
I'm getting the `invalid argument supplied for foreach()` error when I try to use one of my functions. I've looked at some other examples but couldn't find any matching cases. My code is as follows. **User.php:** ``` public function activateAccount($email = null, $email_code = null) { $field = 'email'; $data = $this->_db->get('users', array($field, '=', $email)); if($this->_db->count()) { $this->_data = $this->_db->first(); } if($this->emailExists($email)) { if($this->data()->verified == 0) { $this->updateActivation('users', $email, array( 'verified' => 1 )); return true; } else { return false; } } return false; } public function updateActivation($table, $fields = array(), $email = null) { if(!$this->_db->updateActivation($table, $email, $fields)) { throw new Exception('An unexpected error occurred'); } } ``` **DB.php:** ``` public function updateActivation($table, $email, $fields) { $set = ''; $x = 1; foreach($fields as $name => $value) { $set .= "{$name} = ?"; if($x < count($fields)) { $set .= ', '; } $x++; } $sql = "UPDATE {$table} SET {$set} WHERE email = {$email}"; if(!$this->query($sql, $fields)->error()) { return true; } return false; } ``` If any more code is required, please let me know. Any help is much appreciated. Thanks!
2015/10/15
[ "https://Stackoverflow.com/questions/33152220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4516934/" ]
I think you have the same problem : [UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3 2: ordinal not in range(128)](https://stackoverflow.com/questions/5387895/unicodeencodeerror-ascii-codec-cant-encode-character-u-u2013-in-position-3) So you can use `u'\u2013'.encode('utf8')` :) (to be more specific, use `soup.prettify().encode('utf8')`) Or switch to Python 3 ;)
1,728,847
Searching in the second value of a map i use somthing like the following: ``` typedef std::map<int, int> CMyList; static CMyList myList; template<class t> struct second_equal { typename typedef t::mapped_type mapped_type; typename typedef t::value_type value_type; second_equal(mapped_type f) : v(f) {}; bool operator()(const value_type &a) { return a.second == v;}; mapped_type v; }; ... int i = 7; CMyList::iterator it = std::find_if(myList.begin(), myList.end(), second_equal<CMyList>(i)); ``` Question: How can i do such a find in a single line without supplying a self written template?
2009/11/13
[ "https://Stackoverflow.com/questions/1728847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53420/" ]
Use a selector to select the first or the second element from the value\_type that you get from the map. Use a binder to bind the value (i) to one of the arguments of the `std::equal_to` function. Use a composer to use the output of the selector as the other argument of the equal\_to function. ``` //stl version CMyList::iterator it = std::find_if( myList.begin(), myList.end(), std::compose1( std::bind2nd(equal_to<CMyList::mapped_type>(), i), std::select2nd<CMyList::value_type>())) ; //Boost.Lambda or Boost.Bind version CMyList::iterator it = std::find_if( myList.begin(), myList.end(), bind( &CMyList::mapped_type::second, _1)==i); ```
1,897,139
When I'm loading some content through ajax it returns an jQuery .click event and some elements. But when the ajax content is loaded a couple of times and I click the the button that is bound to the .click event, the action is executed a couple of times. For example the ajax content is: ``` <script type="text/javascript"> $('#click').click(function() { alert('test') }); </script> <input type="button" id="click" value="click here"> ``` If this is refreshed 5 times and I click the button I will get 5 alert boxes. Is there a workaround for this?
2009/12/13
[ "https://Stackoverflow.com/questions/1897139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230719/" ]
the dot means 'the current directory'. If you call javac from within `xcom`, then it will look for `A.class` in `xcom/xcom/A.class`, and won't find it.
11,458,214
I'm using an ExpandableListView to get an expandable list. I have 3 expandable "parent" lists: Price, Details, Notes. I want to be able to add unique child lists for each parent list. But the way its set up now, the same child list is being added for each parent list. How do I make it so I can add unique, separate child lists for Price, Details, and Notes? Here is my code: ``` public class Assignment extends ExpandableListActivity { int listFlag = 0; @SuppressWarnings("unchecked") public void onCreate(Bundle savedInstanceState) { try{ super.onCreate(savedInstanceState); setContentView(R.layout.activity_assignment); SimpleExpandableListAdapter expListAdapter = new SimpleExpandableListAdapter( this, createGroupList(), // Creating group List. R.layout.group_row, // Group item layout XML. new String[] { "Group Item" }, // the key of group item. new int[] { R.id.row_name }, // ID of each group item.-Data under the key goes into this TextView. createChildList(), // childData describes second-level entries. R.layout.child_row, // Layout for sub-level entries(second level). new String[] {"Sub Item"}, // Keys in childData maps to display. new int[] { R.id.grp_child} // Data under the keys above go into these TextViews. ); setListAdapter( expListAdapter ); // setting the adapter in the list. }catch(Exception e){ System.out.println("Errrr +++ " + e.getMessage()); } } //Create Headings of Assignment attributes private List createGroupList() { ArrayList result = new ArrayList(); //Create string array for Topic headings String[] topics = {"Price", "Details", "Notes"}; //Iterate through array of names to lay them out correctly for( int i = 0 ; i < 3 ; ++i ) { listFlag = i; HashMap m = new HashMap(); m.put( "Group Item", topics[i] ); // the key and it's value. result.add( m ); } return (List)result; ``` } ``` @SuppressWarnings("unchecked") private List createChildList() { ArrayList result = new ArrayList(); for( int i = 0 ; i < 3 ; ++i ) { // this -15 is the number of groups(Here it's fifteen) /* each group need each HashMap-Here for each group we have 3 subgroups */ ArrayList secList = new ArrayList(); for( int n = 0 ; n < 1 ; n++ ) { HashMap child = new HashMap(); child.put( "Sub Item", " "test")); secList.add( child ); } result.add( secList ); } return result; } ```
2012/07/12
[ "https://Stackoverflow.com/questions/11458214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1519069/" ]
Override the onPause() method ``` @Override public void onPause() { if( mediaPlayer.isPlaying() ) { mediaPlayer.stop(); } super.onPause(); } ``` This method is called when the user leaves your app via the back button, home button, or if they launch another app (via notification etc)
23,897,934
I'am coding a Multi-Threaded TCP echo server, but the problem is when i call UpdateMessage from ClientHandler class, the RichTextBox's text is not appending. This is the Form1 class that containts the RichTextBox1 Public Class Form1 ``` Const PORT As Integer = 1234 'The port number on which the server will listen for connection. Dim ServerSocket As New TcpListener(PORT) 'The Server Socket that will listen for connections on specified port number. Dim Link As TcpClient 'The Socket that will handle the client. Dim NumberOfClients As Integer = 0 'The total number of clients connected to the server. Dim myThread As Thread 'The thread on which the server will handle the client Dim sc As SynchronizationContext = SynchronizationContext.Current Public Clienthandler As ClientHandler Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnStart.Click ServerSocket.Start() ' UpdateMessage("Server started..") myThread = New Thread(AddressOf AcceptClients) 'Handle the client in a different thread myThread.Start() btnStart.Text = "Started!" btnStart.Enabled = False End Sub Private Sub AcceptClients() 'Keep accepting and handling the clients. While (True) Link = ServerSocket.AcceptTcpClient() 'Accept the client and let the Socket deal with it. NumberOfClients = NumberOfClients + 1 'update the total number of clients Dim ClientAddress As String = Link.Client.RemoteEndPoint.ToString ' UpdateMessage("Client number " & NumberOfClients & " connected from " & ClientAddress) Clienthandler = New ClientHandler Clienthandler.StartClientThread(Link, NumberOfClients) Me.sc.Post(AddressOf Clienthandler.UpdateMessage, "Client number " & NumberOfClients & " connected from " & ClientAddress) End While 'close the sockets Link.Close() 'close the Socket. ServerSocket.Stop() 'Stop the Server Socket. End Sub ``` End Class And here is the ClientHandler class: Public Class ClientHandler ``` Private Link As TcpClient Private ClientNumber As Integer Dim NumberOfMessages As Integer = 0 'The number of messages that client has sent. Dim Stream As NetworkStream 'The stream being used for sending/receiving data over Socket. Dim scHandler As SynchronizationContext = SynchronizationContext.Current Public Sub StartClientThread(Link As TcpClient, ClientNumber As Integer) 'Initialize the class variables with the arguments passed in StartClient Me.Link = Link Me.ClientNumber = ClientNumber 'Start the thread Dim ClientThread As New Thread(AddressOf Chat) ClientThread.Start() UpdateMessage("Thread for client " & ClientNumber & " started!") End Sub ``` Public Sub UpdateMessage2(Message As String) ``` Me.scHandler.Post(AddressOf UpdateMessage2, Message) End Sub Public Sub UpdateMessage(Message As String) Message = vbNewLine & Trim(Message) If Message.Length < 1 Then Message = "empty" End If MessageBox.Show("Updating message!" & vbNewLine & Message) Form1.RichTextBox1.AppendText(Message) End Sub ``` The same problem still exits, the RichTextBox is being updated from UI Thread only.
2014/05/27
[ "https://Stackoverflow.com/questions/23897934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2709945/" ]
To be a bit more specific than Hans Passant, using the form name where an object is expected makes use of the default instance of the form, which is an instance that the system creates and manages for you. The default instance is thread-specific though, which means that there is one default instance per thread. If you use the default instance in a secondary thread then you are using a different object to the one that you displayed on the UI thread. You might read a bit more about default instances here: <http://jmcilhinney.blogspot.com.au/2009/07/vbnet-default-form-instances.html> You need to somehow marshal a method call back to the UI thread and then update the existing form instance on that thread. There are a couple of ways that can be done: 1. Have access to the existing form object and call its Invoke method. 2. Use the `SynchronizationContext` class to marshal the method call to the UI thread and then use the default instance.
1,912,283
I have a user control which accepts a title attribute. I would also like that input inner HTML (ASP Controls also) inside of that user control tag like so: ``` <uc:customPanel title="My panel"> <h1>Here we can add whatever HTML or ASP controls we would like.</h1> <asp:TextBox></asp:TextBox> </uc:customPanel> ``` How can I achieve this? I have the title attribute working correctly. Thanks.
2009/12/16
[ "https://Stackoverflow.com/questions/1912283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/140212/" ]
Implement a class that extends Panel and implements INamingContainer: ``` public class Container: Panel, INamingContainer { } ``` Then, your CustomPanel needs to expose a property of type Container and another property of type ITemplate: ``` public Container ContainerContent { get { EnsureChildControls(); return content; } } [TemplateContainer(typeof(Container))] [TemplateInstance(TemplateInstance.Single)] public virtual ITemplate Content { get { return templateContent; } set { templateContent = value; } } ``` Then in method `CreateChildControls()`, add this: ``` if (templateContent != null) { templateContent.InstantiateIn(content); } ``` And you will be using it like this: ``` <uc:customPanel title="My panel"> <Content> <h1>Here we can add whatever HTML or ASP controls we would like.</h1> <asp:TextBox></asp:TextBox> </Content> </uc:customPanel> ```
26,524,787
I have a `MergedDictionaries` and `DateTemplate` inside a `ResourceDictionary` and everything was fine until I added a `Converter`: ``` <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPFTry"> <local:IsEnabledConverter x:Key="isEnabled"/> <===== causes problem <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Styles.xaml" /> </ResourceDictionary.MergedDictionaries> <DataTemplate x:Key="fileinfoTemplate" DataType="{x:Type local:MyFileInfo}"> ... template stuff </DataTemplate> </ResourceDictionary> ``` Adding the `Converter` line causes this error at the line of `DataTemplate`: ``` Property elements cannot be in the middle of an element's content. They must be before or after the content. ``` Why is causing this error? Note that the code compiles and the Converter works fine if I comment out the `MergedDictionaries`.
2014/10/23
[ "https://Stackoverflow.com/questions/26524787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3974213/" ]
The error tells you the issue: ``` <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPFTry"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Styles.xaml" /> </ResourceDictionary.MergedDictionaries> <!-- Move this here --> <local:IsEnabledConverter x:Key="isEnabled"/> <DataTemplate x:Key="fileinfoTemplate" DataType="{x:Type local:MyFileInfo}"> ... template stuff </DataTemplate> </ResourceDictionary> ``` You are trying to put content before setting properties on the resource dictionary. The error says "property elements" (e.g. `ResourceDictionary.MergedDictionaries`) cannot be in the middle of an elements "content" (e.g. your datatemplate/converters etc) Anything that has a dot `.` must appear at the top of an element as you are essentially setting properties in the XAML. Anything that doesn't have a `.` is content and must appear below any property setters. **Note:** this also works the other way round, properties can also be below all the content if you prefer it that way round
27,666
vf page: ``` <apex:page> <apex:form> <apex:inputtext value={!Value}/> <apex:commandButton value="Reset" onclick="this.form.reset();return false;" /> <apex:commandButton value="Quote List" action="{!showlist}"/> </apex:form> </apex:page> ``` i have two button are there first button is to reset and second button is to show list .when i click on the reset button before click the list it is reset the form when i click the reset button after clicking the list it is not working. How to do This one ?
2014/02/12
[ "https://salesforce.stackexchange.com/questions/27666", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/4045/" ]
I believe this.form.reset **is** in fact resetting your form, but the trouble is, when the "Quote List" button is pressed, to call the controller action showList, this is SETTING your values on the page to their variables in the controller. For example: Form is blank (text value in controller empty) ![step1](https://i.stack.imgur.com/17fVc.jpg) Enter text (text value in controller empty) ![step2](https://i.stack.imgur.com/fN4Vx.jpg) If you click reset here, the text area will be reset to nothing. **If you click Quote List here, then as a commandbutton this will SUBMIT your page to setValue() and it will put "hello" into value.** Therefore, the page, still looks like this ![step3](https://i.stack.imgur.com/fN74X.jpg) but now value = "hello" if you click "reset" the HTML form is in fact reset, but TO THIS value. If you alter the text area (no page reloading has been done) to be this: ![step4](https://i.stack.imgur.com/YL0qS.jpg) and then click Reset.. it will reset the field: ![Step5](https://i.stack.imgur.com/W8S2j.jpg) Therefore the problem is not with the ``` this.form.reset() ``` not working, it is to do with what the QuoteList button is doing to the state of the page/controller values. One way to beat the submission problem would be to remove the "action" attribute from the second button, Quote List, and instead use it to reRender a block of the page, in which you can re-trigger getters to load new lists of items, if this fits your functionality? So your snippet in the question could become something like: ``` <apex:form > <apex:inputtext value="{!value}"/> <apex:commandButton value="Reset" onclick="this.form.reset();return false;" /> <apex:commandButton value="Quote List" rerender="redrawArea" /> </apex:form> <apex:pageBlock id="redrawArea"> {!value} </apex:pageBlock> ``` You then have your logic in the getValue() method (remembering best practises about what should go in a getter of course!).
36,908,926
I am new to programming. I am currently taking python in school right now and I ran into a error and I figure it out. I keep getting a syntax error and I am not sure if it is typo on the instructor or myself. ``` def main(): num_emps=int(input("How many employee records? ")) empfile=open("employee.txt","w") for count in range(1,num_emps+1): print("Enter data for employee#",count,sep='') name=input("Name: ") id_num=input("ID Number: ") dept=input("Department: ") empfile=write.(name+"\n") empfile=write.(id_num+"\n") empfile=write.(dept+"\n") print() empfile.close print("Employee records written to disk") main() ``` I keep getting the error at ``` empfile=write.(name+"\n") ``` or is it supposed to be ``` empfile.write(name+"\n") ``` Thanks for the help
2016/04/28
[ "https://Stackoverflow.com/questions/36908926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6262807/" ]
Use the [`app.makeSingleInstance()`](https://github.com/electron/electron/blob/v0.37.7/docs/api/app.md#appmakesingleinstancecallback) function, there's an example in the docs.
392,775
How can I indicate syntax errors (e.g. an illegal sequence of tokens) in an eclipse editor plugin just like in the eclipse Java editor, i.e. by red wriggly underlines, a red marker on the scrollbar that you can jump to, and an explanatory message when you hover over either one? I'm writing an eclipse editor plugin for a custom file format (specifically, the "snake file format" of the Shark3D game engine). I have implemented a scanner to get syntax highlighting, and an outline. * For the underlines, do I simply have the scanner return an `IToken` with a "wriggly underline" `TextAttribute` instead of the normal one, or is there a specific mechanism for marking syntax errors? * How do I implement the scrollbar markers? Is `IAnnotationModel` the relevant interface here? If so, where do I register the implementation so that the markers appear? * I've only found `SourceViewerConfiguration.getAnnotationHover()`, which would allow me to implement the hover behaviour, but only for the "annotation", which I suppose means the scrollbar markers - how do I implement the hover behaviour for the text itself? I'd be happy specific advice as well as an URL of a tutorial that covers this - the eclipse help documents and examples don't seem to. **Edit:** Markers are the best solutions to this. A working example of how to use them can be found in the plugin example code in `org.eclipse.ui.examples.readmetool.AddReadmeMarkerAction`
2008/12/25
[ "https://Stackoverflow.com/questions/392775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16883/" ]
You should be using Markers. An example derived from "The Java Developer's Guide to Eclipse" follows: ``` <extension point="org.eclipse.core.resources.markers" id="snakesyntax" name="Snake syntax error"> <super type="org.eclipse.core.resources.problemmarker" /> <super type="org.eclipse.core.resources.textmarker" /> <persistent value="true" /> <extension> IMarker marker = res.createMarker("com.ibm.tool.resources.snakesyntax"); marker.setAttribute(IMarker.SEVERITY, 0); marker.setAttribute(IMarker.CHAR_START, startOfSyntaxError); marker.setAttribute(IMarker.CHAR_END, endOfSyntaxError); marker.setAttribute(IMarker.LOCATION, "Snake file"); marker.setAttribute(IMarker.MESSAGE, "Syntax error"); ```
50,433,111
I have a problem I am sitting on for the past few days. I want to write an optimal (in JS) program for verifying if a number is a Palindrome. My current approach: ```js function isPalidrom2(pali){ //MOST time consuming call - I am splitting the digit into char array. var digits = (""+pali).split(""); //To get the length of it. var size = digits.length; var isPali = true; for(var i = 0; i<Math.floor(size/2); i++){ //I am comparing digits (first vs last, second vs last-1, etc.) one by one, if ANY of the pars is not correct I am breaking the loop. if(parseInt(digits[i]) != parseInt(digits[size-i-1])){ isPali = false; break; } } return isPali; } ``` It's not optimal. The biggest amount of time I am waisting is the change from INT to STRING. And I am out of ideas - I tried to understand the BIT operators but I can't. - I tried to google and look for alternative approaches - but I can't find anything. - I tried to play with different algorithms - but this one is the fastest I was able to apply. So in short - my question is: "how can I make it faster?" EDIT: So the task I want to solve: > > Find all of the prime numbers within the range of all five digit numbers. > Among all of the multiplies (i\*j) they are between them, find the most significant palindrome. > > > My current approach: ```js function isPrime(number){ var prime = true; var i for(i = 2; i<= number/2; i++){ if((number%i)==0){ prime = false; break; } } return prime; } function get5DigitPrimeNr(){ var a5DigitsPrime = []; var i; for(i = 10000; i<100000; i++){ if(isPrime(i)){ a5DigitsPrime.push(i) } } return a5DigitsPrime; } function isPalidrom(pali){ var digits = (""+pali).split(""); //we check if first and last are the same - if true, we can progress size = digits.length; return (digits[0]==digits[size-1]) && (parseInt(digits.slice(1, Math.floor(size/2)).join("")) == parseInt(digits.reverse().slice(1, Math.floor(size/2)).join(""))) } function isPalidrom2_48s(str) { var str = str.toString(); const lower = str.substr(0, Math.floor(str.length / 2)); const upper = str.substr(Math.ceil(str.length / 2)); return lower.split("").reverse().join("") === upper; } function isPalidrom_22s(pali){ var digits = (""+pali).split(""); var size = digits.length; for(var i = 0; i<Math.floor(size/2); i++){ //console.log("I am comparing: "+i+", and "+(size-i-1)+" elements in array") //console.log("I am comparing digit: "+digits[i]+", and "+digits[(size-i-1)]+"") if(digits[i] !== digits[size-i-1]){ //console.log('nie sa rowne, koniec') return false; } } return true; } function isPalidrom2_80s(pali){ return parseInt(pali) == parseInt((""+pali).split("").reverse().join("")) } function runme(){ var prime5digits = get5DigitPrimeNr(); var size = prime5digits.length; var max = 0; var message = ""; for(var i = 0; i<size; i++){ for(var j = 0; j<size; j++){ var nr = prime5digits[i]*prime5digits[j]; if(nr>max && isPalidrom2(nr)){ max = nr; message = 'biggest palidrome nr: '+nr+', made from numbers: '+prime5digits[i]+' x '+prime5digits[j]; } } } console.log(message) } function timeMe(){ var t0 = performance.now(); runme(); var t1 = performance.now(); console.log("Function took " + millisToMinutesAndSeconds(t1 - t0) + " s to find the perfect palindrom.") } //helper functons: function millisToMinutesAndSeconds(millis) { var minutes = Math.floor(millis / 60000); var seconds = ((millis % 60000) / 1000).toFixed(0); return minutes + ":" + (seconds < 10 ? '0' : '') + seconds; } ```
2018/05/20
[ "https://Stackoverflow.com/questions/50433111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/261083/" ]
To keep the spirit of you code, you could exit the loop with `return` instead of `break` and use the string directly without converting to an array. Strings have, as arrays, the possibility of an access single character with an index. ```js function isPalidrom2(value) { var digits = value.toString(), length = digits.length, i, l; for (i = 0, l = length >> 1; i < l; i++) { if (digits[i] !== digits[length - i - 1]) { return false; } } return true; } console.log(isPalidrom2(1)); console.log(isPalidrom2(12)); console.log(isPalidrom2(1221)); console.log(isPalidrom2(123)); ```
26,728,834
I want to set the Popup Menu inside the LinearLayout. This is my code. ``` for(int i=0;i<ev.size();i++) { LinearLayout rl1 = new LinearLayout(getActivity()); rl1.setOrientation(LinearLayout.VERTICAL); pum1 = new PopupMenu(getActivity(), view); Event ebn=ev.get(i); CalEvent cal = CalEvent.getCalEvent(ebn.getDescription()); pum.getMenu().add(Menu.NONE,ebn.getColor(),Menu.NONE,ebn.getTitle()); pum.getMenu().add(Menu.NONE,ebn.getColor(),Menu.NONE,cal.event_start); rl1.addView(pum); } ``` I'am facing this error- "The method addView(View) in the type ViewGroup is not applicable for the arguments (PopupMenu)". Please do help me
2014/11/04
[ "https://Stackoverflow.com/questions/26728834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3663600/" ]
This is an interesting and useful function, fit to deal with FFT, to perform Signal Processing and Analysis once FFT is a square matrix with "power of two" dimensions... understanding that a power of two is the result of two elevated to some power, and that there are infinite powers of two greater than n, a better name to the function should be minimum power of two greater than n - we just use it to dimension a collection of signal data to submit it to FFT filter. There follows two options, named minpowof2 and the maxpowof2... ``` def minpowof2(n): '''Minimun Power of Two Greater Than n''' f = 1 if n < 2: return 'try n greater or iqual to 2' while n > 2: n /= 2 f += 1 return 2**f def maxpowof2(n): '''Maximum Power of Two Lower than n''' return int(minpot2(n)/2) ```
6,013
I was wondering why some Esperantists use the *x* system (it isn't in the Esperanto alphabet) instead of *h* (which is in the Esperanto alphabet). Should not it be promoted to *h*, regularized, or something like that?
2020/08/20
[ "https://esperanto.stackexchange.com/questions/6013", "https://esperanto.stackexchange.com", "https://esperanto.stackexchange.com/users/2231/" ]
Two arguments I have encountered for preferring "x" to "h": * Because it is not an existing letter in the Esperanto alphabet, automated conversion is possible, e.g. *sx* could be unambiguously converted to *ŝ*. By contrast, even if combinations like *-sh-* are rare, they could occur in compound words e.g. *dishaki*, so *sh* cannot be reliably converted to *ŝ* (similarly *senchava*, *flughaveno*, etc). * Because it is so near the end of the alphabet, it is almost always the case that a naive lexical sorting will achieve correct alphabetical order. So for example, a naive sorting would put *sxi* after *sorto* (which would be correct, because *ŝi* comes after *sorto*), but would put *shi* before *sorto*. This only fails when a letter to which an accent could be applied is followed by *z*; for example a naive sort would misorder *uxato* (*ŭato*) and *uzi*, but such occurrences are very rare.