source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0000123718.txt" ]
Q: Php Check If a Static Class is Declared How can i check to see if a static class has been declared? ex Given the class class bob { function yippie() { echo "skippie"; } } later in code how do i check: if(is_a_valid_static_object(bob)) { bob::yippie(); } so i don't get: Fatal error: Class 'bob' not found in file.php on line 3 A: You can also check for existence of a specific method, even without instantiating the class echo method_exists( bob, 'yippie' ) ? 'yes' : 'no'; If you want to go one step further and verify that "yippie" is actually static, use the Reflection API (PHP5 only) try { $method = new ReflectionMethod( 'bob::yippie' ); if ( $method->isStatic() ) { // verified that bob::yippie is defined AND static, proceed } } catch ( ReflectionException $e ) { // method does not exist echo $e->getMessage(); } or, you could combine the two approaches if ( method_exists( bob, 'yippie' ) ) { $method = new ReflectionMethod( 'bob::yippie' ); if ( $method->isStatic() ) { // verified that bob::yippie is defined AND static, proceed } } A: bool class_exists( string $class_name [, bool $autoload ]) This function checks whether or not the given class has been defined.
[ "math.stackexchange", "0001279792.txt" ]
Q: Max-min of a function on closed, bounded interval using EVT I'm just having little bit of difficulty with the following question: Find the local maxima and minima of $f : [0, 1] \rightarrow \mathbb{R}$ defined by $$ f(x)=x^4(1-x)^6 $$ So we know the function is differentiable on the open interval $(0,1)$ and hence we can test the nature of the critical points on $(0,1)$. Also, since $f$ is continuous on the closed, bounded interval we can use the Extreme Value Theorem on the end points. But, when we take the first derivative of this function we find that critical points occur at $$x=0,\frac{2}{5},1$$ ie two of the critcal points occur at the end points. The second derivative test shows that the critical point at $\frac{2}{5}$ is a maximum so thats all well and good. However, my question is, how do I test the nature of the two other critical points? Since by the definition of differentiability we can not use the first and second derivative tests on the end points. Is it merely just a matter of arguing that since $f(0)=f(1)=0$ and since by the definition of EVT we know that on a closed, bounded interval a continuous function has both a maximum and a minimum value on that closed, bounded interval and since $x=\frac{2}{5}$ attains the maxima then by EVT $x=0$ and $x=1$ must attain the minima? I would like to make my argument as rigorous as possible. Thanks. A: I am viewing $[0,1]$ as the entirety of the domain. Observe that $f'(x)=2x^3(x-1)^5(5x-2).$ We have $f'(x)=0$ at $x=0,2/5,1.$ Also, $f'(x)>0$ on $(0,2/5),$ $f'(x)<0$ on $(2/5,1).$ Therefore $f(2/5)$ is a local maximum. Moreover, $f'(x)>0$ on $(0,2/5)$ implies that $f(x)\geq f(0)$ on some (relatively) open neighborhood $[0,c)$ about $0.$ We conclude that $f(0)$ is a local minimum. Similarly, $f(x)\geq f(1)$ on a (relatively) open neighborhood about 1 and consequently $f(1)$ is a local minimum.
[ "askubuntu", "0000153801.txt" ]
Q: Permission issues with mounted new hard drive on Ubuntu machine I recently purchased a new hard drive, for the sole purpose of storing a database. I am running Ubuntu 10.0.4. Since I had not done this sort of thing before, I decided to use the GUI (Disk Utility) to format and mount the disk (to avoid any snarfus caused by typos etc at the command line). I correctly identified the new drive and proceeded as follows: Elected to format the drive Selected type: 'Ext4' Selected the 'Take ownership of filesystem' checkbox Unchecked the 'encrypt underlying device' checkbox Provided a name for the new volume (mydata) Once the device had been formatted, I then mounted the device as follows: sudo mount /dev/sdb /mydata I created the directory /mydata/pgdbdata and changed ownership as follows sudo chown -R postgres:postgres /mydata/pgdbdata I check: username@localhost:~$ ls -l /mydata/ total 20 drwx------ 2 root root 16384 2012-06-19 23:05 lost+found drwxr-xr-x 2 postgres postgres 4096 2012-06-20 19:04 pgdbdata However when I change to postgres user: username@localhost:~$ sudo su - postgres postgres@localhost:~$ ls -l /mydata/ ls: cannot open directory /mydata/: Permission denied Because of this permissions issue, I can start the postgresql service and I can't create the postgresql db cluster. I am stuck. What am I doing wrong? A: You have only changed permission of pgdbdata but not of mydata you should be able to do a ls -l /mydata/pgdbdata but if your postgresql user wants to see the content of mydata it has to have read access to that too.
[ "stackoverflow", "0031554038.txt" ]
Q: Mediawiki Upgrade Trouble - PHP Fatal error: Class 'Liuggio\StatsdClient\Factory\StatsdDataFactory' not found I have difficulty upgrading Mediawiki from 1.23 to 1.25 owing to StatsdDataFactory. I succeeded in "composer update" and "php update.php." But when I tried "php rebuildall.php", I got the following error: PHP Fatal error: Class 'Liuggio\StatsdClient\Factory\StatsdDataFactory' not found in /var/www/html/mydomain.com/w/includes/libs/BufferingStatsdDataFactory.php on line 33 The same error occurred both in (1) CentOS 6.6 + PHP 5.3.3 + Apache 2.2.15 + mysql 14.1 and in (2) CentOS 7.1 + PHP 5.4.16 + Apache 2.4.6 + mariadb 15.1 I opened the BufferingStatsdDataFactory.php file. (line 23) use Liuggio\StatsdClient\Factory\StatsdDataFactory; (line 33) class BufferingStatsdDataFactory extends StatsdDataFactory { protected $buffer = array(); ... Then I opened composer.json at /var/www/html/mydomain.com/w/, to find "liuggio/statsd-php-client" is included. "require": { "cssjanus/cssjanus": "1.1.1", "ext-iconv": "*", "leafo/lessphp": "0.5.0", "liuggio/statsd-php-client": "1.0.12", "oojs/oojs-ui": "0.11.3", "php": ">=5.3.3", "psr/log": "1.0.0", "wikimedia/cdb": "1.0.1", "wikimedia/composer-merge-plugin": "1.0.0", "wikimedia/utfnormal": "1.0.2", "zordius/lightncandy": "0.18" }, In this file, I imitated the solution shown here (PHP Fatal error: Class 'MyApp\Chat' not found in /MyApp/chat-server.php). "autoload": { "psr-0": { "ComposerHookHandler": "includes/composer" } "psr-4": { "Liuggio\\": "includes/composer" } }, But it did not work. The following did not work either. "psr-4": { "Liuggio\\": "" } When I commented out the BufferingStatsdDataFactory.php, I got another error: PHP Fatal error: Class 'BufferingStatsdDataFactory' not found in /var/www/html/mydomain.com/w/includes/context/RequestContext.php on line 137 Now my wiki site is inaccessible. I welcome any suggestions. A: Check the vendor/liuggio/statsd-php-client directory. If the classes are not there, you have some kind of Composer problem. If the classes are there, they are probably not included in the file used by Composer to map class names to file paths. (Depending on its configuration, Composer can either locate files on the fly by traversing directories according to the fully qualified class name, or improve autoloading performance a bit by storing a complete class => path mapping in a file. If the autloader is configured one way and the update command which has to regenerate the classmap the other way, you get errors like this.) To fix that, run composer dump-autoload --optimize.
[ "dba.stackexchange", "0000199091.txt" ]
Q: Redshift: Table columns can be found in information_schema.columns but not in pg_catalog.pg_table_def I create a table in Redshift. When I tried to search for the table definition, I get back results from information_schema.columns by running the following query: select * from information_schema.columns where table_name = 'table' and table_schema='schema' However, when I run a query against pg_catalog.pg_table_def, I don't get back any result. select * from pg_catalog.pg_table_def where tablename = 'table' and schemaname = 'schema' Could anyone help me understand why this is happening? The table is created and owned by the account I'm using. A: Check show search_path; to make sure you are on the current path where the table was created. As stated on the original AWS redshift documentation. PG_TABLE_DEF only returns information about tables that are visible to the user. to get what you want you should run set search_path to '$user', '<#your_schema#>'; select * from pg_catalog.pg_table_def where tablename = '<#your_table#>'; Hope that helps.
[ "stackoverflow", "0058354307.txt" ]
Q: Live traffic on port via snmp and discrepancies Iam trying to get data from HP switches and Juniper firewalls and its port via snmp. I am looking for the way how to analyze live traffic on port so I can create a graph of utilization of the ports like on Solarwinds or Observium. So far I have the results I am getting are from the formula on How to calculate traffic on cisco It works fine, however, every couple of readings I get abnormal speeds. I.e. for a virtual interface on the firewall, which is limited to 4MB I get 20+ MB every now and then. I have a cron job which polls the devices every 5 minutes so the formula is using 300 seconds as a delta of time. So the question is, is it possible for a port to be showing these abnormalities or am I doing something wrong? Any insight would be amazing :-) A: The problem is that you are using ifTable defined in RFC1213. It is sort of outdated due to ifInOctets and ifOutOctets are defined as 32-bit counters. So they will overflow and reset real fast and you'll face abnormal results when this happens. I'd suggest switching to ifXTable (IF-MIB) where these counters are defined as 64-bit values.
[ "bitcoin.stackexchange", "0000043805.txt" ]
Q: If SegWit only increases the capacity to only 2-4x only. Wouldn't we have the same issue in a few years again? If I understand correctly. SegWit is one of the solutions to the full 1MB block problem that doesn't require a hard fork. But I've read this only increases the 1MB to maybe about 2-4x only. If that is the case, wouldn't we have the same problem down the line when transactions reach that level again? A: Yes we would. Segwit just gives us time to do a well-prepared hard-fork or give the opportunity/time for some other enhancement (lightning network, sidechains?) to deal with scalability properly. Note that a hard-fork for larger blocks would also just delay the problem. A: Just like a hard-fork blocksize increase SegWit will not solve the scalability issue by itself. Either provides chiefly a fixed factor increase in capacity. SegWit is also a way to kick the can down the road, but in comparison to the hard-fork blocksize increase, it also solves other issues, doesn't require a hard-fork, and makes blocksize increases less problematic: SegWit resolves an issue where transactions require quadratic effort for verification. The problem was highlighted by the "megatransaction" created by f2pool last July. While capacity only increases linearly with bigger blocks, effort to verify blocks increases at a super-linear rate. For SegWit transactions the transaction verification takes linear effort, making bigger blocks cause less of an advantage for the author of the latest block. Hence, SegWit helps reduces centralizing pressure on mining in the face of capacity increases. On-chain scalability is always limited to linear growth anyway: For every transaction that you resolve on-chain, you need to provide the storage space on-chain. While we will be able to go down that route for a bit, it is unsustainable for large amounts of transactions and we wouldn't be able to reach e.g. the transaction counts corresponding to the payment counts of credit card companies. Scalability improvements need to make better than linear use of the blockchain capacity. Unlike a hard-fork blocksize increase, SegWit sets the stage for further improvements in the future. One promising proposal is the Lightning Network, which compounds numerous payments at the cost of two or three on-chain transactions. Another exciting improvement is the introduction of Schnorr signatures. Schnorr signatures are smaller than ECDSA signatures, but due to their homomorphic nature allow for both signature aggregation and key aggregation. In addition, Schnorr signatures enable the use of adaptor signatures that allow for a wide range of smartcontracts to be created with Scriptless Scripts. Last but not least, SegWit introduces Script versioning. This allows to specify which version of Script to use to interpret a transaction, allowing multiple versions of Script to coexist safely at the same time in the network. Script versioning allows much easier deployment of Script improvements to expunge bugs and vulnerabilities, or to add new features like Schnorr signatures.
[ "stackoverflow", "0026282360.txt" ]
Q: 404 error on https://developers.facebook.com/tools/debug/ I am trying to add Facebook like/share to http://labs.jstor.org/shakespeare/macbeth. I’ve tried several different ways of adding it, including the HTML5 and XFBML options from developers.facebook.com and from AddThis. I made sure to include the og: title, type, url, and image meta tags as shown: The open graph debugger tool at developers.facebook.com/tools/debug/ returns a 404. I checked in Firebug to make sure there wasn't a 404 header coming across. When clicked, the like/share buttons show the page as "Page Not Found" What is going on here? A: Check your server code and make sure you're returning the correct meta tags to Facebook - if you have special user agent handling, you might be returning the correct tags to regular browsers but the wrong tags to Facebook, which can make debugging more difficult
[ "stackoverflow", "0030864627.txt" ]
Q: How to make JUnit test fall down if constuctor is present? I am learning JUnit and Test Driven Development practice. I have empty Money interface: public interface Money { } CommonMoney class which implements Money interface: public class CommonMoney implements Money { private CommonMoney() { } public static Money create(String decimalPart, Currency currency) { return new Money() { }; } } And MoneyTest class which tests CommonMoney public class MoneyTest { // some test cases before @Test public void shouldNotCreateCommonMoneyObjectWithEmptyConstructor() { @SuppressWarnings("unused") Money money = new CommonMoney(); fail(); } } For now test case shouldNotCreateCommonMoneyObjectWithEmptyConstructor is red, but it should be green if constructor of CommonMoney is private and red if it is public. Is it possible to make test case like this? And how can I do it? A: Is it possible to make test case like this? Yes, it is possible to implement this test by using java reflection, for example see this question. Otherwise, you cannot test, that the private constructor is present, from outside of that class - the code just won't compile. However, it doesn't really make sense to test this. Access modifiers are really there for developer convenience and to limit the access scope. Arguably, scope limitation is also done for convenience. Your tests should cover public API and not look at private implementation.
[ "stackoverflow", "0046397319.txt" ]
Q: using pdfkit to display pdf I'm trying to load a pdf that is stored in my app, here is the code that I have import UIKit import PDFKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let pdfView = PDFView(frame: UIScreen.main.bounds) let url = Bundle.main.url(forResource: "example", withExtension: "pdf") pdfView.document = PDFDocument(url: url!) self.view.addSubview(pdfView) } When I am running in simulator, I am getting the error that fatal error: unexpectedly found nil while unwrapping an Optional value in the debug are it is showing that url is nil .Any idea how to resolve it? I am running swift 4 and iOS 11 as target A: Please click the checkbox under Target Membership in File Inspector.
[ "stackoverflow", "0022585143.txt" ]
Q: How to get the position of the last visible item inside an Adapter in Android I intend to create a listview with different layout for each visible row. I also set setStackFromBottom(true). I know I can use int getItemViewType(int position) in View getView(int position, View convertView, ViewGroup parent) but it uses the fix position and not based on visible positions. I'd like to use the listview as the following concept shows: If I scroll down, the next item should replace the previous one and use its large layout. I tried it with the following code, but it uses fix position so always the last item in the list is the largest, not the last visible item. @Override public int getItemViewType(int position) { if(position==values.length-1) return 1; return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = null; type=getItemViewType(position); if (type == 0) rowView = inflater.inflate(R.layout.list_item, parent, false); else rowView = inflater.inflate(R.layout.list_item2, parent, false); return rowView; } I reckon, I should get the position of the first and last visible item inside the Adapter, but I don't know how to do it. Can I somehow create a listview that follows the aforementioned concept? Can I get the correct positions? A: You can get a lot of info by setting a scroll listener on the ListView: mListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // firstVisibleItem + visibleItemCount = last item } } However, I can't think of how you could use this info effectively. Even if you change getView() to return a larger View when its position is the same as the last item, you can't easily resize the views as they move up, because getView() won't be called again for items already displayed, unless you call notifyDataSetChanged() on the adapter repeatedly, which would kill performance. My though is to add another View below the ListView that will display the larger View for the item below the last one in the ListView. Make it look like the last row in the ListView. You could change that view in the onScroll() method.
[ "stackoverflow", "0002473270.txt" ]
Q: Contracts vs Exceptions Let's assume I have the following code: public class MainClass { public static void main(String[] args) { System.out.println(sumNumbers(10, 10)); } //@requires a >= 10; //@ensures \result < 0; public static int sumNumbers(int a, int b) { return a+b; } } I can make 2 things here: Use Code Contracts (in this case, what is in comments). When sumNumbers is run and a < 10, it will throw immediatly an exception (although it doesn't seem to be very descriptive): Exception in thread "main" org.jmlspecs.jmlrac.runtime.JMLInternalNormalPostconditionError: by method MainClass.sumNumbers at MainClass.sumNumbers(MainClass.java:500) at MainClass.internal$main(MainClass.java:9) at MainClass.main(MainClass.java:286) or... Throw an exception. The exception can be as descriptive as I want. I'd also to check in the end of the function to see whenever the post conditions are true or not. Which would you use here and why? A: I like the idea of the code contracts, but the descriptive IllegalArgumentException (or similar) tips it for me. It's much clearer in a support/production role (or even a development) to get an explicit exception message, which gives you a head start in diagnosis what's going wrong (whether a system is broken, or if you're misusing an API during development).
[ "stackoverflow", "0003884955.txt" ]
Q: Refresh a region in window before drawing text I'm drawing text on window at WM_PAINT message, is there any way i can refresh that window region before drawing a new line of text so the old text at the same location would get erased? A: You need to call InvalidateRect for the window with the bErase parameter set to TRUE so that it will erase itself before the WM_PAINT is generated. This is often required when the window is a static text control, as those don't erase themselves automatically when you change their value. Make sure your window is handling WM_ERASEBKGND properly and the window class doesn't have a NULL background brush, as this is the mechanism used by InvalidateRect to do the erasing.
[ "stackoverflow", "0000562392.txt" ]
Q: Getting the handle of window in C# I have the following class declared: public partial class MainWindow : Window And I need to get the actual handle of the window once the window has one. How can I do that and where should I put the query function. What I tried so far was: IntPtr hwnd = new WindowInteropHelper(this).Handle; But the handle I get back is 0, which might be because it was planted in OnInitialized - maybe the window is not ready yet at that stage. And, yes - it is connected via WPF, thank you for pointing it out! Thanks A: In the OnInitialized method the handle has not yet been created. But you are on the right track. If you put your call in the Loaded event the handle will have been created and it should return the correct handle. A: The earliest place you can get the handle is OnSourceInitialized
[ "stackoverflow", "0015517692.txt" ]
Q: custom tableviewCells for UITableView created programatically in storyboard In my app I am using storyboard. But I created a UITableView programmatically instead of dragging from Object Library. And now I want to customize the cells of that programmatically created UITableView. Can anyone help me by providing an example of creating a UITableViewCell programmatically in storyboard? A: I'd avoid putting layout and building of your cell into cellForRowAtIndexPath. To create a custom cell programatically you should first create a UITableViewCell subclass. Add to it the labels, imageViews, etc... Add the as subViews of the cell.contentView. PROGRAMATICALLY i.e. - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 21)]; [self.contentView addSubview:_label]; } return self; } If you want to do layout stuff of the cell then in the MyCell class you can do... - (void)layoutSubViews { [super layoutSubviews]; // layout stuff relative to the size of the cell. } Then in the tableViewController you need to register the cell class... In viewDidLoad... [self.tableView registerClass:[MyCell class] forCellReuseIdentifier:@"MyCellIdentifier"]; WITH INTERFACE BUILDER Still create the custom subclass but also create a xib file of the same name. Then in your xib file you can hook up the outlets instead of having to create them in the init of the cell. (If you do it this way then the init will not be called anyway). The only other change you need is that in viewDidLoad you need to register the nib for the cell not the class. Like this... UINib *cellNib = [UINib nibWithNibName:@"MyCell" bundle:nil]; [self.tableView registerNib:cellNib forCellReuseIdentifier:@"MyCellIdentifier"]; Then everything else works the same. USING THE CELL To use the cell that you have created the subclass for... - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCellIdentifier"]; [self configureCustomCell:(MyCell*)cell atIndexPath:indexPath]; return cell; } - (void)configureCustomCell:(MyCell*)cell atIndexPath:(NSIndexPath *)indexPath { // do all you logic of getting any info from arrays etc in here. cell.label.text = @"Blah". } SUMMARY Doing it this way means that your tableviewcontroller is only interested in putting stuff into the cells. If you put all your logic for building your cells as well everything just gets really messy. It also means you don't have to deal with loads of different tags to save and retrieve different UI elements.
[ "stackoverflow", "0054888858.txt" ]
Q: Find next occurance of a given time after given timestamp Given an arbitrary timestamp (e.g. 2019-02-26 10:30:00) I would like to find the next occurrence of an arbitrary time. For example, the next occurrence of 12:00:00 will be 2019-02-26 12:00:00 but the next occurrence of 09:00:00 will be the next day at 2019-02-27 09:00:00. The results could be Carbon or Datetime objects. The test time will just be a string as shown. Is there a way to calculate this in native PHP or PHP Carbon without conditionally boxing in time periods. An obvious way would be to see if the time being tested is past the check time for today, and if it is, taking the result as the check time plus 24 hours (the next day). That feels to me like too much chopping and joining of dates and times, so is there a way to calculate it by considering time to be a simple linear line? All times will be in a single timezone, with DST. Note: the arbitrary datetimes and check times will stay clear of DST changeovers i.e. 01:00 to 02:00 so hopefully they will not be an issue to take into account. A: Short answer is no for PHP (partial answer, I'm no specialist of Carbon but from quick look it's also no, but you can create a macro from following code). However, with a ternary condition the one-liner is simple enough IMHO (replace the second DateTime($str) with DateTime() if you want to compare with current date and time, and change the >= by > if you want next day when time compared is exactly the same): $str = '2019-02-26 10:30:00'; $date1 = ( ($a = (new DateTime($str))->setTime(12,00)) >= (new DateTime($str)) ) ? $a : $a->modify('+1 day'); $date2 = ( ($a = (new DateTime($str))->setTime(9,00)) >= (new DateTime($str)) ) ? $a : $a->modify('+1 day'); echo $date1->format('Y-m-d H:i:s'); //2019-02-26 12:00:00 echo $date2->format('Y-m-d H:i:s'); //2019-02-27 09:00:00 quick note: what you gave us is not a timestamp, but a formatted date.
[ "stackoverflow", "0014398986.txt" ]
Q: iOS 6 - Error in sending data in HTTPBody with POST method Till last night the code was working perfectly, but today i am facing a weird problem. NSString *hostStr = [@"My API string" stringByAppendingString: @"/users/login"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:hostStr]]; [request setHTTPMethod:@"POST"]; NSString *boundary = @"-----FOO"; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; [request addValue:contentType forHTTPHeaderField:@"Content-Type"]; NSData *usernameData = [username dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]; NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]; NSMutableData *body = [NSMutableData data]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Disposition: form-data; name=\"data[login_name]\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:usernameData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Disposition: form-data; name=\"data[password]\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:passwordData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; NSError *error; NSURLResponse *response; NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSString *serverOutput = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]; NSLog(@"%@",serverOutput); Above code gives me following response <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>400 Bad Request</title> </head><body> <h1>Bad Request</h1> <p>Your browser sent a request that this server could not understand.<br /> </p> <p>Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.</p> <hr> <address>Apache Server at MY API URL Port 80</address> </body></html> But for the same lines of code when i comment this part [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Disposition: form-data; name=\"data[login_name]\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:usernameData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Disposition: form-data; name=\"data[password]\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:passwordData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; It gives me following request response {"login_name":"Username or Password is not valid","responseCode":"0"} Means when i am not sending any data in HTTPBody, API call gives me desire response. I have no any idea what is going wrong here. Many Thanks in advance. A: Well. This is something that I never realized could be a problem. As I more and more check my code, I found that there isn't any problem with my code up "there". But the problem was server side. I contacted the server people and they said that they have enabled some ModSecurity so a multipart form data was not able to be sent in the HTTPBody. This cost me two whole days to figure out. Hope it saves some one's time.
[ "stackoverflow", "0029344511.txt" ]
Q: Ember Documentation understanding - Model linked to Template or not? I'm learning Ember right now and i'm beeing a bit confused because of the Docu of Ember and the getting started example. In the Documentation it says: In Ember.js, templates get their properties from controllers, which decorate a model. And Templates are always connected to controllers, not models. But after doing the getting started guide i'm not sure if this is correct. I've uploaded the finished TodoMVC app here: https://github.com/Yannic92/stackOverflowExamples/tree/master/Ember/TodoMVC In the Index.html you'll find this template: <script type="text/x-handlebars" data-template-name="todos/index"> <ul id="todo-list"> {{#each todo in model itemController="todo"}} <li {{bind-attr class="todo.isCompleted:completed todo.isEditing:editing" }}> {{#if todo.isEditing}} {{edit-todo class="edit" value=todo.title focus-out="acceptChanges" insert-newline="acceptChanges"}} {{else}} {{input type="checkbox" checked=todo.isCompleted class="toggle"}} <label {{action "editTodo" on="doubleClick"}}>{{todo.title}}</label> <button {{action "removeTodo"}} class="destroy"></button> {{/if}} </li> {{/each}} </ul> </script> My question refers to the 3rd Line: {{#each todo in model itemController="todo"}} The Controller todo is only needed to provide the actions for the todos. The data is accessable even without this controller. In my opinion there is the model directly connected with the template isn't it? Or is there a default Controller like the docu mentioned here? For convenience, Ember.js provides controllers that proxy properties from their models so that you can say {{name}} in your template rather than {{model.name}}. A: As you can see in this line: <script type="text/x-handlebars" data-template-name="todos/index"> this is the template for / because the router has this line: this.route('todos', { path: '/'}). Which will have a controller named TodosController, even if you didn't write one ember will generate one for you. So when you delete it that's what happens. In this template you loop through the todo's list. Each of these Todo models are decorated with a controller the TodoController. And with this line: {{#each todo in model itemController="todo"}} you tell ember to use this TodoController for every element in the list. If you leave out the itemController ember assumes the todo's are part of the model for the IndexController provided by the IndexRoute. By default ember has an empty controller which proxies everything to the underlying model. (Note: I believe this will change in ember 2.0). So it may look like it's directly coupled to the model. But you could write a controller that changes everything without changing the model.
[ "stackoverflow", "0020662714.txt" ]
Q: Breakpoint that activates only when variable hits a specific value I am debugging a program that has a lot of for loops, each one with hundreds of values to loop through. Within all this, I'd like to determine that behaviour of a variable when it reaches a certain value. However, to do so, I would have to manually cycle step through all the loops and make sure not to space out. It would take me hours. Is there a way to set a breakpoint that only activates when the variable is a certain value? A: What you're looking for is called conditional breakpoints. Visual Studio 2010 does support conditional breakpoints, you can just create your breakpoint, right click it and then click on Condition. A: Just insert in the cycle something like If(Variable==value) { int unuseful=0; } and set the breakpoint on the operation inside the if A: Create a conditional breakpoint. These can be set up to break when the value at an address changes, which is useful if you are looking for when a variable is set the value of a variable equals a particular value, which is the case you are looking for There are other nice uses of conditional breakpoints so you don't have to put a hard breakpoint as you noted.
[ "stackoverflow", "0018928895.txt" ]
Q: C random number This is my code #include <stdio.h> #include <stdlib.h> main() { int r = rand() % 20; printf("%d", r); } I want to get a random number 19 and below, but it just gives me 1 every time I compile and run it. Can someone show me what I am doing wrong? A: Try #include <stdio.h> #include <stdlib.h> int main() { srand(time(NULL)); int r = rand() % 20; printf("%d", r); } Note: Using the % is not a great way to get an even distribution. See: Recommended way to initialize srand? for more info.
[ "stackoverflow", "0007596162.txt" ]
Q: Get by reflection properties of class ,but not from inherited class class Parent { public string A { get; set; } } class Child : Parent { public string B { get; set; } } I need to get only property B, without property A but Child.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance) return both properties :/ A: You should add BindingFlags.DeclaredOnly to your flags, i.e: typeof(Child).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly) A: Try using the DeclaredOnly binding flag. It should limit the properties returned to only those declared on the class you are interested in. And here is a code sample: PropertyInfo[] properties = typeof(Child).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly); A: Add BindingFlags.DeclaredOnly
[ "stackoverflow", "0017262984.txt" ]
Q: C++ Error: no match for call to ‘(std::string {aka std::basic_string}) (std::string&)’ I'm new to C++. I search many times, but still can't get the answer. I'm writing a class named Course to describe the courses students taking at school. The Course class has 3 fileds: protected: string courseName; int courseNum; float score; And I have a public method "setName" to set the course name: Course &setName(string name) { this->courseName(name); return (*this); } However, when I tried to compile, the compiler complains that: C++ Error: no match for call to ‘(std::string {aka std::basic_string}) (std::string&)’ I also tried to modify the code to Course &setName(string &name)... And the compiler keeps complaining about the same error. But if I change the code to: Course &setName(string name) { this->courseName = name; return (*this); } Then it works well. I couldn't understand what the compiler is complaining about and why I can't use the direct initialization? A: I couldn't understand what the compiler is complaining about and why I can't use the direct initialization? Because that's not an initialization. That's an assignment. Both assignment an (copy-)initialization make use of the = sign, but don't let that fool you: the two things are fundamentally different. Initialization is what gives a value to an object upon construction. When your setName() member function gets called, the object on which it is invoked (as well as its data members) have already been constructed. If you want to initialize them there, you're late: you've missed the train. In a constructor's initialization list, on the other hand, you could initialize your data members as follows: Course::Course(std::string name) : courseName(std::move(name)) { } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ // This would be initialization
[ "stackoverflow", "0041009530.txt" ]
Q: iOS - NSDateFormatter dateFromString returns nil only in one case I'm testing some values for a date format ("dd-MM-yyyy") and there's a special case that I can't explain: var datef = NSDateFormatter() datef.dateFormat = "dd-MM-yyyy"; var date_a = "02-01-1990" var date_b = "01-01-1990" var date_f_a = datef.dateFromString(date_a); var date_f_b = datef.dateFromString(date_b); data_f_a returns Jan 2, 1990, 12:00 AM, but date_f_b returns nil. Any other date will return the expected value, except for January 1st, 1990. If I add datef.lenient = true date_f_b is no longer nil, but I shouldn't need to do that. Why is it an invalid date? EDIT 1: It happens the same if I use DateFormatter(): EDIT 2: Xcode version: 8.1 A: After a few comments, it has been determined that the code in the question is being run with the locale of es_PE. This is the country of Peru. The date in question is January 1, 1990. By default, NSDateFormatter uses the local timezone and when parsing date strings that have no time, midnight is assumed. In Peru, in the year 1990, day light savings began at midnight, January 1st, 1990. This means that clocks went from December 31, 1989 at 11:59:59pm straight to January 1, 1990 at 1:00:00am. There was no midnight on January 1, 1990. This is why the attempt to convert the string 01-01-1990 failed for this user. There was no midnight for this date in Peru (and possibly a few other locales, if any, that had day light saving start at the same time). Most people testing this code would claim it works just fine since most people testing this code don't live in Peru. I found a useful website with helpful information. See http://www.timeanddate.com/time/change/peru/lima?year=1990 for details about Peru and day light savings time. Note that in 1989 and 1991, Peru did not use day light savings time.
[ "stackoverflow", "0004790096.txt" ]
Q: Setting initial value for DataType.DateTime in model I'm passing a model to a view, and the model contains this attribute: [Required(ErrorMessage = "Please enter a start date")] [DataType(DataType.DateTime)] [DisplayName("Start Date")] public DateTime StartDate { get; set; } And I have this in my view: <%: Html.TextBoxFor(m => m.StartDate) %> When I load the page, the textbox is populated with a date: 1/1/0001 12:00:00 AM Is there a way to not have this happen, maybe by using metadata? A: In the constructor, programmatically set the StartDate property to the date you want to use as the default. (Such as DateTime.Today.) If you want the value to be initially empty, try using a Nullable<DateTime> which will default to null.
[ "stackoverflow", "0003711649.txt" ]
Q: Perl split with empty text before/after delimiters I was noticing some curious behavior with Perl's split command, particularly in cases when I would expect the resulting array to contain empty strings '', but it actually doesn't. For example, if I have a delimiter(s) at the end (or the beginning) of the string , the resulting array does not have an empty string(s) '' as the last (or first) element. Example: @s = split(/x/, 'axb') produces 2 element array ['a','b'] @s = split(/x/, 'axbx') produces same array @s = split(/x/, 'axbxxxx') produces same array But as soon as I put something at the end, all those empty strings do appear as elements: @s = split(/x/, 'axbxxxxc') produces a 6 element array ['a','b','','','','c'] Behavior is similar if the delimiters are at the beginning. I would expect empty text between, before, or after delimiters to always produce elements in the split. Can anyone explain to me why the split behaves like this in Perl? I just tried the same thing in Python and it worked as expected. Note: Perl v5.8 A: From the documentation: By default, empty leading fields are preserved, and empty trailing ones are deleted. (If all fields are empty, they are considered to be trailing.) That explains the behavior you're seeing with trailing fields. This generally makes sense, since people are often very careless about trailing whitespace, for example. However, you can get the trailing blank fields if you want: split /PATTERN/,EXPR,LIMIT If LIMIT is negative, it is treated as if an arbitrarily large LIMIT had been specified. So to get all trailing empty fields: @s = split(/x/, 'axbxxxxc', -1); (I'm assuming you made a careless mistake when looking at leading empty fields - they definitely are preserved. Try split(/x/, 'xaxbxxxx'). The result has size 3.)
[ "stackoverflow", "0030061428.txt" ]
Q: Heap Corruption Detected C++ Custom Vector Hey I am rehashing through a few old projects in a class I took and as I'm redoing this project I keep getting this error when my clear() function is called in the driver, Heap Corruption Detected: after Normal block (#142) CRT detected that the application wrote to memory after the end of the HEAP buffer Here is my custom Vector class #include "MyVector.h" //insert header files #include <iostream> #include <string> //setup access to necessary libraries using namespace std; MyVector::MyVector() { // initialize member data size = 0; capacity = 2; //initialize new array classArray = new int[capacity]; } MyVector::MyVector(int maxCapacity) { // initialize member data size = 0; capacity = maxCapacity; // initialize new array classArray = new int[capacity]; } MyVector::~MyVector() { if (classArray != NULL) { delete [] classArray; classArray = NULL; } } int MyVector::getSize() { return size; } int MyVector::getCapacity() { return capacity; } void MyVector::clear() { // delete the array delete[] classArray; // reinitialize the array capacity = 2; size = 0; classArray = new int[capacity]; } void MyVector::push_back(int n) { if (size > capacity) { // setup the special case of an array with 0 elements if (size == 0) { clear(); } else { // declare a temporary pointer and allocate a new array capacity = capacity * 2; int* tempArray = new int[capacity]; // copy the values from the old array to the temporary array for (int i = 0; i < size; i++) { tempArray[i] = classArray[i]; } // call the destructor delete[] classArray; // assign the classArray pointer to the new array classArray = tempArray; } } // pushback a new value to the array classArray[size] = n; // increment size size++; } int MyVector::at(int n) { // check if n is within the bounds of the array if (n >= size) { throw n; } // if not return the value of the index requested else { return classArray[n]; } } and here is my driver code, //insert header files #include <iostream> #include <string> #include "MyVector.h" //setup access to necessary libraries using namespace std; //declare constants #pragma region Constants const int TEST_VALUE1 = 21; const int TEST_VALUE2 = 31; const int TEST_VALUE3 = 41; const int MAX = 12; #pragma endregion int main() { // Create a default vector MyVector sam; // push some data into sam cout << "\nPushing three values into sam"; sam.push_back(TEST_VALUE1); sam.push_back(TEST_VALUE2); sam.push_back(TEST_VALUE3); cout << "\nThe values in sam are: "; // test for out of bounds condition here // and test exception for (int i = 0; i < sam.getSize() + 1; i++) { try { cout << sam.at(i) << " "; } catch (int badIndex) { cout << "\nOut of bounds at index " << badIndex << endl; } } cout << "\n--------------\n"; // clear sam and display its size and capacity sam.clear(); //********ERROR BEING THROWN HERE********* cout << "\nsam has been cleared."; cout << "\nSam's size is now " << sam.getSize(); cout << "\nSam's capacity is now " << sam.getCapacity() << endl; cout << "---------------\n"; // Push 12 values into the vector - it should grow cout << "\nPush 12 values into sam."; for (int i = 0; i < MAX; i++) sam.push_back(i); cout << "\nSam's size is now " << sam.getSize(); cout << "\nSam's capcacity is now " << sam.getCapacity() << endl; cout << "---------------\n"; cout << "\nTest to see if contents are correct..."; // display the values in the vector for (int i = 0; i < sam.getSize(); i++) { cout << sam.at(i) << " "; } cout << "\n--------------\n"; cout << "\n\nTest Complete..."; cout << endl; system("PAUSE"); return 0; } I've looked back and forth at my old project several times and I can't see why I am getting this error when I am trying to delete something. I mean it sounds like that usually happens when I am trying to allocate something that can't be allocated but not deleted? Any help appreciated thanks! A: Your push_back code can be reduced to: if (size > capacity) { // resize } classArray[size] = n; size++; But note that you start with size == 0 and capacity == 2, then have three calls to push_back. On the third one, size == 2 and capacity == 2. size > capacity is still false, so you'll write into classArray[2] (without having resized) which is uninitialized memory. This is undefined behavior. You want to check size >= capacity to resize. Note that there's another serious problem with your class: you failed to write a copy constructor, so if you copied it, both copies would attempt to deallocate the same memory. See Rule of Three (updated in C++11 to Rule of Five).
[ "stackoverflow", "0006348768.txt" ]
Q: Inno Setup: How to change Messages at runtime? I need to change Messages at runtime. I have a AfterInstall procedure that checks to see if a bat file was successful. If it is not, I want to change the value of ExitSetupMessage just before calling WizardForm.Close. I was hoping to do something like this english.ExitSetupMessage := 'THIS IS THE PART THAT DOES NOT WORK';. Code examples would be appreciated. Thank you. [Languages] Name: english; MessagesFile: compiler:Default.isl [Files] Source: {src}\test.bat; DestDir: {tmp}; AfterInstall: ValidateInstall [Code] procedure ValidateInstall(); var ResultCode : Integer; begin if not Exec(ExpandConstant('{tmp}\test.bat'), '', '', SW_HIDE, ewWaitUntilTerminated, ResultCode) then begin english.ExitSetupMessage := 'THIS IS THE PART THAT DOES NOT WORK'; WizardForm.Close; end; end; A: I don't know of a way to change the messages at runtime. However in the case you posted I know of a workaround. You would set your CustomState before calling WizardForm.Close var CustomState : Boolean; procedure CancelButtonClick(CurPageID: Integer; var Cancel, Confirm: Boolean); var Msg : String; Res : Integer; begin Confirm := False; // Don't show the default dialog. // Chose which message the custom or default message. if CustomState then Msg := 'My Custom Close Message' else Msg := SetupMessage(msgExitSetupMessage); //as the Question Res := MsgBox(Msg, mbConfirmation,MB_OKCANCEL); // If they press OK then Cancel the install Cancel := (Res = IDOK); end; The side effect is you lose the Exit Setup? title of the dialog box. You can use function ExitSetupMsgBox: Boolean; when you don't want to change the message to keep the title around.
[ "stackoverflow", "0050408612.txt" ]
Q: c#: Convert object to a generic list I've got a data structure in which a variable is of type object. However, I know during runtime this object will be definitely a List<T>, where T should cover multiple cases (e.g., int, string, ...). In the following code, I'd like to use List<T>-specific functionality, such as Linq functions. With the following check, I make sure, it's a list: if (constantExpression.Value.GetType().GetGenericTypeDefinition() == typeof(List<>)) { // Want to use Linq here } Is this possible? Unfortunately, I've found nothing helpful on the Web. A: If it's ok for you to handle your list as a List<object>() you can do the following: var listOfObjects = ((IEnumerable)constantExpression.Value).Cast<object>(); That's far from perfect but it's probably the best you can get if you don't want to resort to using reflection or using dynamic, as suggested in the comments.
[ "travel.stackexchange", "0000042970.txt" ]
Q: App or website to calculate change in Cambodian riel and US dollars Here in Cambodia there's a fairly unique two-currency system in use, and it often gets really confusing to work out if you're getting the correct change. The local currency is the Cambodian riel and the de facto currency is the US dollar. There are no US coins here. In common street transactions USD $1 is equal to KHR 4,000. (Though at a money changer it's more like 4,100 riel to the dollar, it's not relevant for this question.) So very often riel notes are used as the equivalent to coins and you have to do some tricky mental arithmetic to calculate what your change should be. You might be given a price in dollars and cents, in dollars and riels, or just in riels. You might receive your change in dollars and riels, or just in riels. So I'm looking for an app or website that can do these calculations for me, more reliably than my poor little brain. A: I hacked up a basic version of such an app as a single-page of HTML with Javascript. Then MeNoTalk came along and made it pretty! When you edit any of the fields in the "price" or "paid" sections, all the other fields update. Not as you type but when you hit enter after editing. The bottom section tells you how much change you should get. It's doesn't attempt to use any kind of official or true exchange rate between the two currencies that you would only find in a bank or money changers, just the usual de facto shopping rate of 4,000 riel to one dollar that you'll find here everywhere. You can get the "current version" straight from PasteBin or try it in JSFiddle. I've also put it up on GitHub as a gist so you can hack it and contribute your changes back. A: Apparently Google can convert multiple currencies to one. In the example showed it sums 1 British Pound, 2 US Dolars, 10 Swiss Francs and 1000 Indian Rupees and converts it to Euros. But when I try to sum any currency with Cambodian Riels it doesn't seem to work. Perhaps it's a bug or I don't know how to make Google understand what I wish.
[ "stackoverflow", "0057103313.txt" ]
Q: How do I perform IOCTLs on a device in a macos kernel extension? In my Network Kernel Extension i need to modify the firewall rules. So i need to issue some ioctl()s to the /dev/pf device - what is the best way to achieve this? I can't seem to find any kernel APIs for opening a device and then performing the relevant ioctl commands. EDIT: Yes i know NKEs are deprecated, but unfortunately I cannot do what I want in the Network Extension API just yet. A: The function VNOP_IOCTL, declared in <bsd/vnode_if.h>, looks like it should do what you want, but I've not tried it myself: *! @function VNOP_IOCTL @abstract Call down to a filesystem or device driver to execute various control operations on or request data about a file. @discussion Ioctl controls are typically associated with devices, but they can in fact be passed down for any file; they are used to implement any of a wide range of controls and information requests. fcntl() calls VNOP_IOCTL for several commands, and will attempt a VNOP_IOCTL if it is passed an unknown command, though no copyin or copyout of arguments can occur in this case--the "arg" must be an integer value. Filesystems can define their own fcntls using this mechanism. How ioctl commands are structured is slightly complicated; see the manual page for ioctl(2). @param vp The vnode to execute the command on. @param command Identifier for action to take. @param data Pointer to data; this can be an integer constant (of 32 bits only) or an address to be read from or written to, depending on "command." If it is an address, it is valid and resides in the kernel; callers of VNOP_IOCTL() are responsible for copying to and from userland. @param ctx Context against which to authenticate ioctl request. @return 0 for success or a filesystem-specific error. */ extern errno_t VNOP_IOCTL(vnode_t vp, u_long command, caddr_t data, int fflag, vfs_context_t ctx); struct vnop_select_args { struct vnodeop_desc *a_desc; vnode_t a_vp; int a_which; int a_fflags; void *a_wql; vfs_context_t a_context; }; It's exported as part of the BSD KPI.
[ "stackoverflow", "0006395915.txt" ]
Q: Implementing Observer Pattern for my Rails App I am currently using rails 3.0.7 and ruby 1.9.2 and making a rails App which contains a video being loaded from a database while being rendered by FlowPlayer. and a set of slides based on the video. Now, I wanted to synchronize the slides with the video. For the timings, I am asking the user to enter the timings of each slide. So, I was wondering if i could use observer pattern for this by making a sort of central time as the subject and the video and slides as the observers? While, the concept seems correct after going through a number of tutorials on the net, I am not able to proceed or ge ideas on coding it. Any help would be greatly appreciated. A: basically, you have two choices: use ActiveRecord's callbacks (before_save, after_save, etc..) or create an observer # app/observers/some_model_observer.rb class SomeModelObserver < ActiveRecord::Observer observe :your_model # the model you're observing def after_create(record) end # other ActiveRecord callbacks end
[ "stackoverflow", "0026936646.txt" ]
Q: Can't get Compute Engine instances list I'm testing out Compute Engine and am hitting a snag. I've set up a project (jwl-project-1) and created an instance (instance-1). After authenticating with gcloud auth login, I set the project like this: gcloud config set project jwl-project-1 And then tried to get a list of instances: gcloud compute instances list In return, I get this error: ERROR: (gcloud.compute.instances.list) Some requests did not succeed: - Invalid value for project: jwl-project-1 I basically accepted the default values for project and instances (micro-disk). What am I missing? A: As the error indicates there is no project called 'jwl-project-1' under your account. Try to use your Project ID instead: $ gcloud config set project <project-id>
[ "ru.stackoverflow", "0000893621.txt" ]
Q: Покадровая анимация png Есть ~100 файлов png нужно их как бы анимировать, весят они от 8кб до 4мб. Но как то через чур всё тормознуто выходит. Можно ли тут что то оптимизировать или сделать более правильно ? int counter = 0; DispatcherTimer dT = new DispatcherTimer(); public Png() { InitializeComponent(); dT.Interval = new TimeSpan(0, 0, 0, 0, 25); dT.Tick += new EventHandler(dT_Tick); dT.Start(); } void dT_Tick(object sender, EventArgs e) { var image = new BitmapImage(new Uri("C:\\" + counter + ".png")); imageKonteiner.Source = image; counter++; if (counter == 100) { dT.Stop(); } } UPD - Пробовал и так заранее в память запихать, вышло тоже не очень(, память процесса подпрыгивает до 4гб : int counter = 0; DispatcherTimer dT = new DispatcherTimer(); private BitmapImage[] images; public Png() { InitializeComponent(); images = new BitmapImage[100]; for(int i = 0 ; i < images.Length; i++) { images[i] = new BitmapImage(new Uri("C:\\" + i + ".png")); } dT.Interval = new TimeSpan(0, 0, 0, 0, 25); dT.Tick += new EventHandler(dT_Tick); dT.Start(); } void dT_Tick(object sender, EventArgs e) { imageKonteiner.Source = images[counter]; counter++; if (counter == 100) { dT.Stop(); } } A: У меня оригинальные изображения в 1920 x 1080 и отображать их нужно в том же размере. Что то похожее на screensaver у Windows такие изображения отрисовать быстро(на всех компьютерах) невозможно. Все упирается или в количество оперативки(загрузить все обьекты) или в быстроту работы винчестера(считать каждую картинку на НЕдефрагментированном диске будет довольно медленная задача, но с ССД выйдет быстренько) _ Можно пойти неправильным путем: Сделать FIFO-list (в шарпе это Queue) и при помощи его сделать буфер картинок, и картинки подгружать на 10-15 штук относительно того что сейчас используется. Кароче, буферизация изображений в нужном количестве размером(подбирается опытным путем оптимальный из соображений занятая оперативка/быстрота работы). А так же не забываем диспоузить изображения что б оперативу освобждать! Внутри FIFO сохранять, скажем, инстансы структуры: Index Image Так же иметь Array путей. Индекс аррея будет равнятся индексу элемента FIFO. Но имеет в себе полный список путей изображений что бы понятно было с какого пути нужно будет грузить следующую картинку. Собственно, если индекс превышает количество ячеек - нужно начинать с первой. Этот буфер в отдельном потоке подгружает нужное количество изображений, скажем, до 15 элементов начиная с занаддного индекса (картинка которая сейчас отрисовывается). Заданный индекс меняется в то время, как отрисовывается теперешний твой кадр. Можно пойти ВОЗМОЖНО правильным путем (GIF): Смонтировать большую гифку и подгружать ее. Я не уверен сработает ли этот путь т.к. не знаю как гифки сохраняются в оперативке. Вполне возможно что как набор BMP кадров... Так что может и не сработать. А можно пойти ПРАВИЛЬНЫМ путем (Video): Смонтировать видео, заменить Transparancy слой на хрома-кей, сжать его в x264 и потом проигрывать по кругу ВИДЕО обрабатывая хромакей. Это оптимальнее с точки зрения занимаемого места и проще в реализации(видео отобразить) Если же там полупрозрачные поверхности есть.... То смонтировать видео, экспортировать в видеоформат с поддержкой альфа-канала(RGBA), сжать его в x264. А потом реализовать поддержку обработки альфа-канала в твоей программе. теперь на тему: и память процесса переваливала за 4гб, хотя файлов там было на 1гб. это потому, что ты подгружаешь в BMP (Bitmap) то есть в несжатую картинку. По-другому не выйдет.
[ "dba.stackexchange", "0000141504.txt" ]
Q: Microsoft SQL Server creating an Inline function Hey guys I'm completely new to SQL where I have to write a user-defined function (UDF) that calculates a student's GPA for a given time frame. The Inputs are StudentId int, ClassStartDateStart datetime, and ClassStartDateEnd datetime. Where the output should be the student's GPA for all classes that were taken between ClassStartDateStart and ClassStartDateEnd. Also, supply the script to call this new function, passing it parameter values of your choice. I tried creating a code but don't know where to start. Here is what I have so far: USE [Master] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION GPAofStudents (StudentID int, ClassStartDateStart datetime, ClassStartDateEnd datetime) RETURNS decimal(3,2) AS BEGIN DECLARE AvgGPA decimal(5,2); SET AvgGPA = (SELECT AVG(Class_GPA) FROM Students_Classes WHERE Student_ID = StudentID AND Start_Date > ClassStartDateStart AND Start_Date <= ClassStartDateEnd AND Class_GPA > 0; RETURN AvgGPA; END; My table for the students is this: CREATE TABLE [dbo].[Students_Classes]( [Student_Class_ID] [int] IDENTITY(1,1) NOT NULL, [Student_ID] [int] NOT NULL, [Class_ID] [int] NOT NULL, [Start_Date] [date] NOT NULL, [Assignment1] [int] NULL, [Assignment2] [int] NULL, [Assignment3] [int] NULL, [Assignment4] [int] NULL, [Class_GPA] [int] NULL, CONSTRAINT [Student_Class_ID] PRIMARY KEY CLUSTERED ( USE [A_University_Database] INSERT INTO Students_Classes ([Student_ID],[Class_ID],[Start_Date],[Assignment1],[Assignment2],[Assignment3], [Assignment4],[Class_GPA]) VALUES ('1', '5', '2010-05-30', '86', '92', '69', '99', NULL), ('1', '6', '2010-05-30', '86', '92', '69', '99', NULL), ('2', '2', '2010-05-30', '99', '85', '91', '79', NULL), ('2', '7', '2010-05-30', '99', '85', '91', '79', NULL), ('3', '3', '2010-10-01', '67', '91', '71', '100', NULL), ('3', '4', '2010-10-01', '67', '91', '71', '100', NULL), ('4', '5', '2009-02-21', '56', '93', '72', '86', NULL), ('4', '6', '2009-02-21', '56', '93', '72', '86', NULL) What I have to do is create an aggregate inline function that displays the students class GPA. Do I need to create a stored procedure first that way the inputs are recognized? A: Do I need to create a stored procedure first that way the inputs are recognized? You are missing @ symbols at the beginning of each parameter. Find out more about writing functions here Once you know the basics this article by Jeremiah Peschka explains the benefits of inline functions and much more. Basically if your table valued function is not inline then it will execute once for every row returned by the calling query. This can be very inefficient. An inline table valued function can be referred to as a parameterised view. Your function is a scalar function which will always execute once for each row but it could be converted to an inline table valued function with the code below. CREATE FUNCTION dbo.GPAofStudents (@StudentID int, @ClassStartDateStart date, @ClassStartDateEnd date) RETURNS TABLE WITH SCHEMABINDING AS RETURN SELECT @StudentID AS Student_ID, AVG(Class_GPA) AS GPA FROM dbo.Students_Classes WHERE Student_ID = @StudentID AND Start_Date > @ClassStartDateStart AND Start_Date <= @ClassStartDateEnd AND Class_GPA > 0; Using the WITH SCHEMABINDING option will stop anyone from editing the schema used by your function and breaking it.
[ "stackoverflow", "0010517436.txt" ]
Q: Zend Framework submiting 2 forms with 1 submit Okay this might sound simple but there's a catch. I'll try and explain the situation. I have a page wich is build with a layout and in the center there's a view with 2 buttons and a normal form. The 2 buttons are to switch between two input forms. When the submit is pressed both forms are submitted. The first form is for general information and the second one is used to upload an image along with the information if so desired. Now to avoid the question why not use one form? it's a request to keep the two seperated in this manner. So i was considering going with 2 views where the top 2 buttons would act like a submit, creating a POST request with the form data but not actually submiting it to the database. And then redirecting towards the second view where you can upload images. And then when the actual submit button is pressed i want all the data collected to be written into the database. Basically it's like a page with 2 Tabs with a form each and only 1 submit button to submit the forms on both tabs. I just can't get my head around how to create those 2 buttons to store the post data and then have the 'final' submit button use the previous post data and then other form data to create a new combined post data to store in the database. Anyone have an idea how to accomplish this? Am i approaching this correctly or is there a simpler or cleaner method to doing this? Thanks in advance! A: You have a number of options here, one option is to create one form and add your two seperate sections as SubForms, i.e. instances of Zend_Form_SubForm. Then you can style the forms separately, tab them but keep one submit button for both. Also when you submit, the forms data will be separated into an array element for each of the sub forms. you can see more about this here: http://framework.zend.com/manual/en/zend.form.advanced.html#zend.form.advanced.multiPage another solution i'm fond of is using an action helper to split the process of adding the forms into two pages, similarly to the url above but storing form information inside a session object until both have been validated and then processing both forms at once. http://framework.zend.com/wiki/display/ZFPROP/Zend_Controller_Action_Helper_Multiform+Proposal+-+Simon+Mundy http://framework.zend.com/wiki/pages/viewpage.action?pageId=42130 hope this helps.
[ "electronics.stackexchange", "0000030017.txt" ]
Q: Which configuration is better for pulling down an NPN transistor's base? I was discussing on pull down resistors with a colleague of mine. Here are the two configurations for transistor as a switch. The input signal can either come from a microcontroller or an another digital output to drive a load, or from an analogue signal to give a buffered output from the collector of the transistor to the microcontroller. On the left, with Q1, is my colleague's configuration. He states that: A 10K resistor is needed directly in the base to prevent the Q1 from switching ON unintentionally. If the configuration on the right, with Q1, is used, then the resistance will be too weak to pull the base down. R2 also protects \$V_{BE}\$ from over-voltage and give stability in case of temperature changes. R1 protects from over-current to the Q1's base, and will be a bigger value resistor in case the voltage from "uC-out" is high (in example +24V). There is going to be a voltage divider formed, but that doesn't matter as the input voltage is high enough, already. On the right, with Q2, is my configuration. I think that: Since an NPN transistor's base is not a high impedance point like a MOSFET or a JFET, and the \$H_{FE}\$ of the transistor is less than 500, and at least 0.6V is needed to turn the transistor ON, a pull-down resistor is not critical, and in most cases is not even needed. If a pull-down resistor is going to be put in the board, then the value of exact 10K is a myth. It depends on your power budget. A 12K would do fine as well as a 1K. If the configuration on the left, with Q1, is used, then a voltage divider is created and may create problems if the input signal, that is used to switch the transistor ON, is low. So, to clarify things, my questions are: Is 10K pull-down resistor a rule-of-thumb that I should apply everytime? What are the things to consider when determining a pull-down resistor's value? Is the pull-down resistor really needed in every application? In what cases the pull-down resistor is needed? Which configuration would you prefer and why? If none, what would be a better configuration? A: Summarised Solution: The two configurations are close to equivalent. Either would work equally well in almost all cases. In a situation where one was better than the other the design would be excessively marginal for real world use (as anything so crucial to make the two differ substantially means the operation is "right on the edge"). . \$R_{2}\$ or \$R_{4}\$ are needed only when \$V_{in}\$ can be open circuit, which in that case they are a good idea. Values up to about 100K are probably OK in most cases. 10k is a good safe value in most cases. A secondary effect in bipolar transistors (which I have alluded to in my answer) means that R2 and R4 may be needed to sink Icb reverse bias leakage current. If this is not done then it will be carried by the be junction and can cause device turn on. This is a genuine real world effect which is well known and well documented but not always well taught in courses. See my answer addition. Left hand case: Drive voltage is decreased by \$\frac{10}{11}\$, which means 9% less. Base sees 10K to ground, if input is open circuit. If input is LOW, then base sees about 1K to ground. Actually 1K//10K = essentially the same. Right hand case: Drive = 100% of \$V_{in}\$ is applied via 1K. Base sees 10K to ground if \$V_{in}\$ is open circuit. (as opposed to 11K). If the input is LOW, base sees 1K, which is essentially the same. R2 and R4 act to shunt the base leakage current to ground. For low power or small signal jellybean transistors, up to several Watts rating, this current is very small, and usually will not turn the transistor ON, but it just might in extreme cases - so say 100K would usually be enough to keep the base LOW. This only applies if \$V_{in}\$ is open circuit. If \$V_{in}\$ is grounded, which means it is LOW, then R1 or R5 are from base to ground and R2 or R4 are not needed. Good design includes these resistors if \$V_{in}\$ may ever be open circuit (e.g. a processor pin during startup may be open circuit or undefined). Here is as an example where a very short "blip" due to a pin floating was of major consequence: A very long time ago, I had a circuit controlling an 8 track open reel data tape drive. When the system was first turned on the tape would run backwards at high speed and despool. This was "very very very annoying". The code was checked and no fault was found. It turned out that the port drive went open circuit as the port initialized and this allowed the floating line to be pulled high by the tape deck which put a rewind code on the tape port. It rewound! The initialisation code did not explicitly command the tape to stop as it was assumed that it was already stopped and would not start by itself. Adding an explicit stop command meant that the tape would twitch but not despool.(Counts on fingers of the brain - hmmm 34 years ago. (That was at the very start of 1978 - now almost 38 years ago as I edit this answer). Yes, we had microprocessors back then. Just :-). Specifics: A 10K resistor is needed directly in the base to prevent the Q1 from switching ON unintentionally. If the configuration on the right, with Q1, is used, then the resistance will be too weak to pull the base down. No! 10K = 11K for practical purposes 99.8% of the time, and even 100k would work in most cases. R2 also protects VBE from over-voltage and give stability in case of temperature changes. No practical difference in either case. R1 protects from over-current to the Q1's base, and will be a bigger value resistor in case the voltage from "uC-out" is high (in example +24V). There is going to be a voltage divider formed, but that doesn't matter as the input voltage is high enough, already. Some merit. R1 is dimensioned to provide desired base drive current so yes. \$R_{1} = \dfrac{V}{I} = \dfrac{(Vin - Vbe)}{I{desired\, base\, drive}}\$ As \$V_{BE}\$ low and you design for more than enough current, then: \$R_{1} \cong \dfrac{Vin}{Ib_{desired}}\$ \$I_{base \ desired} >> \frac{Ic}{\beta}\$ - where \$\beta\$ = current gain. If \$\beta_{nominal} = 400\$ (eg BC337-40 where \$\beta =\$ 250 to 600) then design for \$\beta \leq 100\$ unless there are special reasons not to. For instance, if \$\beta_{nominal} = 400\$ then \$\beta_{design} = 100\$. If \$Ic_{max} = 250mA \$ and \$V_{in} = 24V \$ then $$I_b = \frac{I_c}{\beta} = \frac{250}{100} = 2.5mA $$ $$ R_b = \frac{V}{I} = \frac{24V}{2.5mA} = 9.6k \Omega$$ We could use 10k, as beta is conservative but 8.2k or even 4.7k is ok. $$ Pr_{4.7k} = \frac{V^2}{R} = \frac{24^2}{4.7k} = 123mW $$ This would be ok with a \$\frac{1}{4}W\$ resistor but 123mW may not be totally trivial so one may wish to use the 10k resistor instead. Note that switched collector power = V x I = 24 x 250 = 6 Watts. On the right, with Q2, is my configuration. I think that: Since an NPN transistor's base is not a high impedance point like a MOSFET or a JFET, and the HFE of the transistor is less than 500, and at least 0.6V is needed to turn the transistor ON, a pull-down resistor is not critical, and in most cases is not even needed. As above - sort of, yes, BUT. ie base leakage will bite you sometimes. Murphy says that without the pull-down it will accidentally fire the potato cannon into the crowd just before the main act, but that a 10k to 100k pull-down will save you. If a pull-down resistor is going to be put in the board, then the value of exact 10K is a myth. It depends on your power budget. A 12K would do fine as well as a 1K. Yes! 10k = 12k = 33k. 100k MAY be getting a bit high. Note that all this applies only if Vin can go open circuit. If Vin is either high or low or anywhere in between then the path through R1 or R5 will dominate. If the configuration on the left, with Q1, is used, then a voltage divider is created and may create problems if the input signal, that is used to switch the transistor ON, is low. Only in very very very very extreme cases as shown. $$ I_{R1} = \frac{V}{R} = \frac{V_{in}-V{be}}{R1} $$ $$ I_{R2} = \frac{V_{be}}{R_2} $$ So the fraction that R2 will "steal" is $$ \frac{I_{R2}}{I_{R1}} = \frac{\frac{V_{be}}{R_2}} { \frac{V_{in}-V_{be}}{R_1}} $$ $$ \frac{I_{R2}}{I_{R1}} = \frac{R_1}{R_2} \times \frac{V_{be}}{V_{in}-V_{be}} $$ If \$R_1 = 1k \$, \$R2 = 10K\$ then $$\frac{R_1}{R_2} = 0.1 $$ and if \$V_{be} = 0.6V \$, \$V_{in} = 3.6V \$ (to make sums clearer) then $$ \frac{V_{be}}{V_{in}-V_{be}} = \frac{0.6}{3.0} = 0.2 $$ So overall fraction of drive lost is \$ 0.1 \times 0.2 = 0.02 = 2\% \$ i.e even with 1k/10k the loss of drive is minimal. If you can judge Beta and more so closely that 2% drive loss matters then you should be in the space program. Orbital launchers work with safety margins in the 1% - 2% range in some key areas. When your payload to orbit is 3% to 10% of your launch mass (or less) then every % of safety margin is a bite out of our lunch. The latest North Korean orbital launch attempt used an actual safety margin of -1% to -2% somewhere critical, apparently, and "summat gang aglae". They are in good company - the US and USSR lost many many many launchers in the early 1960s. I knew a man who used to build atlas missiles early on. What fun they had. One Russian system NEVER produced a successful launch - too complex.) UK launched one satellite ever FWIW. ADDED It has been suggested in comments that R2 and R4 are never needed, because an NPN is a CURRENT-controlled device. R2 and R4 would only make sense for VOLTAGE-controlled devices, like MOSFETs and How can a pull-down be needed when the MCU output is hi-Z, and the transistor is controlled by current? This suggestion in various forms has been repeated by enough people that it is worth emphasising. If a bipolar transistor base is left floating then reality AND the relevant data sheet information both demonstrate that a small amount of collector current can flow under specified conditions. The conditions where this typically can occur are described below. I have personally seen real-world situations where this effect caused spurious turn-on problems. If your worst case situation, using worst case (not typical) datasheet parameters, does not fulfill these conditions and/or the results do not concern you worst case, then a base pull down is not strictly essential. There is an important secondary effect in bipolar transistors which results in R2 and R4 having a useful and sometimes essential role. I'll discuss the R2 version as it is the same as the R4 version but slightly "purer" for this case (ie R1 becomes irrelevant). If Vin is open circuit then R2 is connected from base to ground. R1 has no effect. base APPEARS to be grounded with no signal source. However, the CB junction is effectively a reverse biased silicon diode. Reverse leakage current will flow through the CB diode into the base. If no external path to ground is provided this current will then flow via the forward biased base-emitter diode to ground. This current will notionally result in a collector current of Beta x Icb leakage but at such low currents you need to look at the underlying equations and/or published device data. A BC337 - datasheet here has a Icb cutoff of about 0.1 uA with Vbe = 0. Ice0 = collector base current is about 200 nA in this case. Vc is 40V in that example but the current approximately doubles per 10 degrees C rise and that spec is at 25C and the effect is relatively voltage independent. The two are closely related. At around 55c you may get 1 uA - not much. If usual Ic is 1 mA then 1 uA is irrelevant. Probably. I have seen real world circuits where omission of R2 caused spurious turn on problems. With R2 = say 100k then 1 uA will produce 0.1V voltage rise and all is well. A: At the risk of throwing fuel on the fire of such a highly contentious issue, I will add my two groats worth. The OP mentions "another digital output" or an "analogue signal" as a possible driving signal. At the risk of stating the obvious, the resistor values should be chosen so that the driving source is guaranteed to turn the transistor on and off under worst case conditions. If the \$V_{OL(MAX)}\$ of the source is greater than 0.6V, R4 will indeed be needed. This could be the case for example, if the driving source is an op-amp without a rail-to-rail output, or a digital transistor output with a high saturation voltage. Similarly, R1 and R2 should be chosen so that the transistor's base current is sufficient to turn the transistor on with the source at \$V_{OH(MIN)}\$. As ever, consult the appropriate data sheets and design accordingly. A: The left one looks like it provides a voltage divider to lower the base voltage, but that isn't true: the base voltage is just \$V_{BE}\$, or around 0.65V for low currents. R2 will only cause a slightly higher current from the microcontroller's output, but at 65\$\mu\$A it's nothing to worry about. And yes, R2 will pull the base down if the microcontroller's pin is Hi-Z. Add it if it eases your mind, though transistors don't start conducting if no voltage is applied to the base. With R2 present changes in \$V_{BE}\$ will cause less change in \$I_B\$ than when R2 is not there, but the effect is negligible. In the right one R4 only causes an unnecessary current path from the output pin to ground. This will be higher than R2 will see, if the microcontroller runs at 5V it will be 500\$\mu\$A. R4 only has a function if the microcontroller's pin is Hi-Z. Because of the larger current for R4 than for R2 I would prefer the left solution. If I would place R2/R4 in the first place. Which I probably wouldn't.
[ "electronics.stackexchange", "0000104456.txt" ]
Q: Understanding GPIO analog and digital I'm trying to understand GPIO, and have read a bunch of different blog posts and I think I'm close to getting it, but still struggling with a few things. I've seen a few reference to GPIO only being able to work with binary values, but other posts which say the value can be from 0-255. I'm assuming this is the difference between analog and digital GPIO. Is that correct? Is it possible that a single GPIO pin can act as both analog and digital? A: A GPIO pin is a 'general purpose input/output' pin. This is by default only high or low (voltage levels, high being the micro controller's supply voltage, low usually being ground, or 0V). But the levels of 'high' and 'low' are usually given as voltages as a proportion of the supply voltage. So anything usually above 66% of the supply voltage is considered a logic level 'high' which means some lower voltage devices can talk with high voltage devices as long as the levels fall within what is considered 'high'. A 1.8–2.7V low power microcontroller or GPS receiver for example will have trouble communicating directly to a 5V microcontroller because what the low voltage device sees as 'high' the higher voltage device will not think it's high at all. This is for using GPIO as an input pin, and output is basically the same - the output high is based on the supply of the controller, where it will drive current out and set the voltage of that pin to VCC, or sink current and pull the pin to 0V for a logic 'low'. Sometimes you can use a SINGLE pin for 'analog' values, by configuring the GPIO pin to be used by other onboard devices like an 'analog to digital' (ADC) converter. The pin is set to a channel on the ADC and this acts as an input to the ADC now, not a normal GPIO pin. You can then set the ADC to take a sample, and read the ADC's result register value for numbers like 0-1024 if it's 10-bit resolution. As someone has mentioned, a GPIO pin could be used in software to give the effect of a Pulsed Width Modulation (PWM) signal, usually at low speeds for GPIO toggling. Most microcontrollers have dedicated PWM generators which can be configured to use a GPIO pin as an output pin, and these are very fast and far more stable than using software to control GPIO for generating a PWM signal. PWM are used for 'average' or '%' style signals and allow you to do things like dim lights and control a motor's speed. GPIO pins are usually arranged in groups, called Ports. In small controllers, they might be 8-bit architecture, so ports are often grouped into lots of 8, and their values can be read all at the same time by reading a 'data register' that represents the logic high/low values of those pins. Similarly, you can set pins to be outputs and then write 8-bits into a data register, and the microcontrollers GPIO controller will read the register's changed values, and drive the pin high or pull the pin low depending what value you just set. In newer controllers such as the ARM Cortex A8 and A9 like in the Raspberry Pi and BeagleBone, their GPIO controllers and different options are very complicated. They use a 32-bit architecture, so most GPIO pins are arranged into 32-pin blocks, even if not all are actually usable (some might be dedicated or not enabled). The BeagleBone (which I have worked on before) has some really awesome options for its large amount of pins, and sometimes you will need to use a 'pin mux' tool, which allows you to set up the special modes of certain pins for things like PWM, pulse capture, timer outputs, analog (ADC) channel inputs, and even (on the BeagleBone anyway) mapping to the industrial sub-processors available on the ARM core, but are considered independent processors and need their own pin mapping in order to be connected to the outside world. A: You are most likely referring to Arduino's analog out, which often uses a GPIO pin with software PWM. GPIO typically have three states. Output High, Output Low, and Input/High-Z (High Impedance, where it doesn't affect the output). PWM rapidly toggles an output from Output High to Output low (period), to create an average (Duty Cycle), allowing for something that looks like an analog value. By toggling a Binary GPIO at a 50% (or 128) duty cycle, the output is still binary, but averages out to half way between High and Low. Think of a light bulb. You see it On, or Off. But it's really turning on and off 60 times per second, so fast that you don't notice its blinking really fast. But turn the light bulb on and off manually really slowly, and you notice its blinking. By 255, it means 100% on, and less than 255 is a fraction of 100% on. That's how a Binary GPIO can act like a 255 state Analog pin.
[ "stackoverflow", "0025314237.txt" ]
Q: Why relative path doesn't work in Ruby require I'm starting learning Ruby, one thing that I don't understand, why relative path for require directive doesn't work in ruby. It's something that works almost in every scripting language that I now (JSP, PHP...). I explain with a real example. I have a folder named shapes which contains 3 classes shape, rectangle and square. I have also another file test_shapes.rb from where I call and test my classes. When I import my classes to the main file like this: require "./shape" require "./rectangle" require "./square" I got error for files not found. When I include the name of my subfolder like this: require "./shapes/shape" require "./shapes/rectangle" require "./shapes/square" The code is perfectly working. Because I specified the whole path to the root directory of the project (the lib folder I think). When I include I include the absolute path to the hard disk, like this: require "#{File.dirname(__FILE__)}/shape" require "#{File.dirname(__FILE__)}/rectangle" require "#{File.dirname(__FILE__)}/square" It's also working perfectly. So, I just want some explanation if know why the first import method (the relative path to the current folder) in not working. A: Relative path is based on working dir. I assume that there is main file on the same directory. If you run ruby ./shapes/main.rb on project root, ruby try to find {project_root}/shape.rb, not {project_root}/shapes/shape.rb. It doesn't work. You need to use require_relative like below. # {project_root}/shapes/main.rb require_relative './shape' require_relative './rectangle' require_relative './square' A: You are using relative path. And they are relative to the place where your script is executed. Generally it is bad idea. You should use either absolute path, either relative path to exact file where require is executed. require File.expand_path("../shape", __FILE__) PS: require_relative looks more laconic
[ "stackoverflow", "0011807720.txt" ]
Q: Error to launch winghci shipped in haskell platform package 2012.2.0.0 Everytime I double click winghci.exe an error message CreateGHCiProcess failed with failed with error 2 pops. I assume the installation hasn't completed setting environment variables successfully since cmd C:\>ghci ends up with no command found either. Could anyone help posting changes that might take place during the installation or any solution to this? A: To complete the incomplete answer: add the path of the bin directory inside your haskell platform folder, e.g. C:\Programs\Haskell Platform\2012.2.0.0\bin, to your PATH. That should be all.
[ "stackoverflow", "0018949413.txt" ]
Q: Mixing C++ and Objective-C (Cocoa) resulting in Segmentation Fault I'm trying to learn my way around Objective-C and read a few tutorials about wrapping Objective-C classes into C++. I got to the following point, where everything compiles without any errors, but when I run the program it results in a "Segmentation Fault". Ok, let's say I have the following snippets, which I compile with: g++ -Wall -pedantic -framework Cocoa -x objective-c++ -o test test.mm. Where am I going wrong? test.mm #include <iostream> #import "test-osx.m" struct OpenControllerImpl { OpenController* wrapped; }; class Panel { OpenControllerImpl* impl; public: Panel() : impl(new OpenControllerImpl) { impl->wrapped = [[OpenController alloc] init]; } ~Panel() { [(OpenController*)impl release]; } void open() { [(OpenController*)impl doOpen:impl->wrapped]; } }; int main() { Panel* openPanel = new Panel(); openPanel->open(); return 0; } test-osx.h #import <Cocoa/Cocoa.h> @interface OpenController : NSObject { } - (void)doOpen:(id)sender; @end test-osx.m #import "test-osx.h" #include <stdio.h> @implementation OpenController - (void)doOpen:(id)sender { printf("here"); } @end A: [(OpenController*)impl doOpen:impl->wrapped]; you are casting the struct holding the Objective-C object to the object type. You have to use [impl->wrapped doOpen:…] You don't need to cast, because impl->wrapped already is of pointer to OpenController object type.
[ "math.stackexchange", "0002960497.txt" ]
Q: Do the local polynomials of Weil representations coincide if they are Artin representations (factor through a finite quotient)? Let $K$ be a local field, $G_K$ its absolute Galois group, $I_K$ the inertia subgroup of $G_K$, $\operatorname{Frob}_K \in G_K$ be a Frobenius element, i.e. any element of $G_K$ acting as $x \mapsto x^{|k|}$ on $\bar{k}$, the algebraic closure of the residue fiel $k$ of $K$, $W_K$ be the Weil group of $K$ and $\rho$ be a Weil representation, i.e. it is a representation $\rho: W_K \to \operatorname{GL}_n(\mathbb{C})$ with $\rho(I_K)$ being finite. The local polynomial $P(\rho,T)$ is the inverse characteristic polynomial of $\operatorname{Frob}_K^{-1}$ on the inertia invariants of $\rho$, i.e. $$ P(\rho,T) = \det(1-\operatorname{Frob}_K^{-1} T \, | \, \rho^{I_K}). $$ We say that $\rho$ factors through a finite quotient if there is a finite Galois extension $F/K$ such that $\operatorname{Gal}(\bar{K}/F) \subset \ker{\rho}$ ($\rho$ is also called an Artin representation then). This means that $\rho$ comes from a representation $\bar{\rho}: \operatorname{Gal}(F/K) \to \operatorname{GL}_n(\mathbb{C})$. We can define a local polynomial for $\bar{\rho}$ the same way: $$ P(\bar{\rho},T) = \det(1-\operatorname{Frob}_{F/K}^{-1} T \, | \, \bar{\rho}^{I_{F/K}}) $$ where $I_{F/K}$ is the inertia subgroup of $\operatorname{Gal}(F/K)$ and $\operatorname{Frob}_{F/K} \in \operatorname{Gal}(F/K)$ is any Frobenius element. Question Do we have $ P(\rho,T) = P(\bar{\rho},T)$? For me, it is especially difficult to understand the first definitions without $F/K$ because I am not able to compute them explicitly. Could you please help me with this question? Thank you in advance! A: $\DeclareMathOperator{\Gal}{Gal}$$\DeclareMathOperator{\Frob}{Frob}$ This comes down to checking a few things. Let $\kappa(K), \kappa(F)$ be the residue fields of $K$ and $F$. Let $\rho: \operatorname{Gal}(\overline{K}/K) \rightarrow \operatorname{GL}(V)$ be a continuous, finite dimensional representation of the Weil group. Suppose that the kernel of $\rho$ contains $\operatorname{Gal}(\overline{K}/F)$, so we have a well defined homomorphism $\overline{\rho}: \Gal(F/K) \rightarrow \operatorname{GL}(V)$. The inertia group $I_K$ is the kernel of the surjective homomorphism $$\Gal(\overline{K}/K) \rightarrow \Gal(\kappa(K)^{\operatorname{sep}}/\kappa(K))$$ and the inertia group $I_{F/K}$ is the kernel of the surjective homomorphism $$\Gal(F/K) \rightarrow \Gal(\kappa(F)/\kappa(K))$$ First, a given $\sigma \in \Gal(\overline{K}/K)$ induces the Frobenius on $\Gal(\kappa(K)^{\operatorname{sep}}/\kappa(K))$ if and only if its image in $\Gal(F/K)$ induces the Frobenius on $\Gal(\kappa(F)/\kappa(K))$. Second, the image of $I_K$ in $\Gal(F/K)$ is equal to $I_{F/K}$. Thus $$\{v \in V : \rho(\sigma)v = v \textrm{ for all } \sigma \in I_K\} = \{v \in V : \overline{\rho}(\sigma)v = v \textrm{ for all } \sigma \in I_{F/K}\}$$ or $\rho^{I_K} = \rho^{I_{F/K}}$.
[ "stackoverflow", "0041978340.txt" ]
Q: How to read 4 bytes of data from a given char pointer in C Scenario is that, i wanna read 4 bytes of data from a given pointer which is of type char. Eg: Consider the following - int a=0; char* c; // This will have some address What i wanna do is read 4 bytes starting from c (i.e. the address) and assign them in variable a which is an integer. My Solution: a = *(int*)c; // Assembly is LDR r1, [r6,#0x00] My Problem: Above solution works well on some architectures but fails on some. To be specific, in my case, it fails on Arm CortexM0. If any one has any portable, highly efficient(with minimum assembly) replacement of my solution please share, it would be a great help to me and I thank you for that in advance ;) Please ask if more info needed. A: The problem could be because of alignment. Some CPU architectures can't read or write non-byte values on unaligned addresses. The solution is to make unaligned byte-access instead, which can easily be done with memcpy: memcpy(&a, c, sizeof a); A: There are at many different problems here. Alignment. The char pointer must point at an aligned address if you wish to read an integer at that address. Signedness of char. It is implementation-defined whether char is treated as signed or unsigned. It is therefore a bad type to use for any form of bit/byte manipulation. Instead, use uint8_t. Pointer aliasing. Casting a raw address pointed at by a char* to an int* is undefined behavior as it violates the so-called strict aliasing rule. This could cause your code to get incorrectly optimized by the compiler (particularly gcc). The other way around, from int* to char* would have been fine though. Endianess is not an issue if the stored integer is already in the same endianess format as that of the current system. If not, you'd have to convert it, but that's quite unrelated to the question here... Example of a portable, safe solution: #include <stdint.h> #include <assert.h> #include <string.h> #include <stdio.h> #include <inttypes.h> int main (void) { int x = 123; uint8_t* c = (uint8_t*)&x; // point to something that is an int assert((uintptr_t)c % _Alignof(uint32_t) == 0); // ensure no misalignment uint32_t i; memcpy(&i, c, sizeof(i)); // safely copy data without violating strict aliasing printf("%"PRIu32, i); // print 123 return 0; }
[ "ru.stackoverflow", "0001129104.txt" ]
Q: Долой веб админку для сайта Всем привет! Появился вариант при разработке сайта исключить web админку заменив ее специальной программой работающей с api сайта. Как я считаю это будет намного безопаснее веб админки так как чтоб получить доступ надо скачать ПО, знать лог и пасс + 2х факторная авторизация НУ или же на угад тыкаться в api сайта. В случае с веб админкой достаточно найти url который ведет на авторизацию и начинать взлом =) Возможно, у вас есть опыт в данном направлении, буду рад если поделитесь своими соображениями и информацией! A: А что мешает просто прикрутить двухфакторную авторизацию к админке + установить лимит попыток входа? ПО нужно будет держать на всех устройствах, где может понадобиться доступ к админке. Устройства могут иметь разную ОС, разную архитектуру... Мне кажется, это вызовет больше проблем, чем прибавит в безопасности... В конце концов, и веб-админку можно разместить на другом домене или неявном поддомене.
[ "stackoverflow", "0008693342.txt" ]
Q: Drawing a simple line graph in Java In my program I want to draw a simple score line graph. I have a text file and on each line is an integer score, which I read in and want to pass as argument to my graph class. I'm having some trouble implementing the graph class and all the examples I've seen have their methods in the same class as their main, which I won't have. I want to be able to pass my array to the object and generate a graph, but when calling my paint method it is asking me for a Graphics g... This is what I have so far: public class Graph extends JPanel { public void paintGraph (Graphics g){ ArrayList<Integer> scores = new ArrayList<Integer>(10); Random r = new Random(); for (int i : scores){ i = r.nextInt(20); System.out.println(r); } int y1; int y2; for (int i = 0; i < scores.size(); i++){ y1 = scores.get(i); y2 = scores.get(i+1); g.drawLine(i, y1, i+1, y2); } } } For now I have inserted a simple random number generator to fill up my array. I have an existing frame and basically want to instantiate the Graph class and mount the panel onto my frame. I'm really sorry that this question seems so jumbled by the way, but I've had little sleep... The code in my main statement is: testFrame = new JFrame(); testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Graph graph = new Graph(); testFrame.add(graph); I'm not sure exactly what an SSCE is but this is my attempt at one: public class Test { JFrame testFrame; public Test() { testFrame = new JFrame(); testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Graph graph = new Graph(); testFrame.add(graph); testFrame.setBounds(100, 100, 764, 470); testFrame.setVisible(true); } Graph.java public class Graph extends JPanel { public Graph() { setSize(500, 500); } @Override public void paintComponent(Graphics g) { Graphics2D gr = (Graphics2D) g; // This is if you want to use Graphics2D // Now do the drawing here ArrayList<Integer> scores = new ArrayList<Integer>(10); Random r = new Random(); for (int i : scores) { i = r.nextInt(20); System.out.println(r); } int y1; int y2; for (int i = 0; i < scores.size() - 1; i++) { y1 = (scores.get(i)) * 10; y2 = (scores.get(i + 1)) * 10; gr.drawLine(i * 10, y1, (i + 1) * 10, y2); } } } A: Problems with your code and suggestions: Again you need to change the preferredSize of the component (here the Graph JPanel), not the size Don't set the JFrame's bounds. Call pack() on your JFrame after adding components to it and before calling setVisible(true) Your foreach loop won't work since the size of your ArrayList is 0 (test it to see that this is correct). Instead use a for loop going from 0 to 10. You should not have program logic inside of your paintComponent(...) method but only painting code. So I would make the ArrayList a class variable and fill it inside of the class's constructor. For example: import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.Stroke; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.swing.*; @SuppressWarnings("serial") public class DrawGraph extends JPanel { private static final int MAX_SCORE = 20; private static final int PREF_W = 800; private static final int PREF_H = 650; private static final int BORDER_GAP = 30; private static final Color GRAPH_COLOR = Color.green; private static final Color GRAPH_POINT_COLOR = new Color(150, 50, 50, 180); private static final Stroke GRAPH_STROKE = new BasicStroke(3f); private static final int GRAPH_POINT_WIDTH = 12; private static final int Y_HATCH_CNT = 10; private List<Integer> scores; public DrawGraph(List<Integer> scores) { this.scores = scores; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); double xScale = ((double) getWidth() - 2 * BORDER_GAP) / (scores.size() - 1); double yScale = ((double) getHeight() - 2 * BORDER_GAP) / (MAX_SCORE - 1); List<Point> graphPoints = new ArrayList<Point>(); for (int i = 0; i < scores.size(); i++) { int x1 = (int) (i * xScale + BORDER_GAP); int y1 = (int) ((MAX_SCORE - scores.get(i)) * yScale + BORDER_GAP); graphPoints.add(new Point(x1, y1)); } // create x and y axes g2.drawLine(BORDER_GAP, getHeight() - BORDER_GAP, BORDER_GAP, BORDER_GAP); g2.drawLine(BORDER_GAP, getHeight() - BORDER_GAP, getWidth() - BORDER_GAP, getHeight() - BORDER_GAP); // create hatch marks for y axis. for (int i = 0; i < Y_HATCH_CNT; i++) { int x0 = BORDER_GAP; int x1 = GRAPH_POINT_WIDTH + BORDER_GAP; int y0 = getHeight() - (((i + 1) * (getHeight() - BORDER_GAP * 2)) / Y_HATCH_CNT + BORDER_GAP); int y1 = y0; g2.drawLine(x0, y0, x1, y1); } // and for x axis for (int i = 0; i < scores.size() - 1; i++) { int x0 = (i + 1) * (getWidth() - BORDER_GAP * 2) / (scores.size() - 1) + BORDER_GAP; int x1 = x0; int y0 = getHeight() - BORDER_GAP; int y1 = y0 - GRAPH_POINT_WIDTH; g2.drawLine(x0, y0, x1, y1); } Stroke oldStroke = g2.getStroke(); g2.setColor(GRAPH_COLOR); g2.setStroke(GRAPH_STROKE); for (int i = 0; i < graphPoints.size() - 1; i++) { int x1 = graphPoints.get(i).x; int y1 = graphPoints.get(i).y; int x2 = graphPoints.get(i + 1).x; int y2 = graphPoints.get(i + 1).y; g2.drawLine(x1, y1, x2, y2); } g2.setStroke(oldStroke); g2.setColor(GRAPH_POINT_COLOR); for (int i = 0; i < graphPoints.size(); i++) { int x = graphPoints.get(i).x - GRAPH_POINT_WIDTH / 2; int y = graphPoints.get(i).y - GRAPH_POINT_WIDTH / 2;; int ovalW = GRAPH_POINT_WIDTH; int ovalH = GRAPH_POINT_WIDTH; g2.fillOval(x, y, ovalW, ovalH); } } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } private static void createAndShowGui() { List<Integer> scores = new ArrayList<Integer>(); Random random = new Random(); int maxDataPoints = 16; int maxScore = 20; for (int i = 0; i < maxDataPoints ; i++) { scores.add(random.nextInt(maxScore)); } DrawGraph mainPanel = new DrawGraph(scores); JFrame frame = new JFrame("DrawGraph"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); } } Which will create a graph that looks like so: A: Just complementing Hovercraft Full Of Eels's solution: I reworked his code, tweaked it a bit, adding a grid, axis labels and now the Y-axis goes from the minimum value present up to the maximum value. I planned on adding a couple of getters/setters but I didn't need them, you can add them if you want. Here is the Gist link, I'll also paste the code below: GraphPanel on Gist import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.Stroke; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class GraphPanel extends JPanel { private int width = 800; private int heigth = 400; private int padding = 25; private int labelPadding = 25; private Color lineColor = new Color(44, 102, 230, 180); private Color pointColor = new Color(100, 100, 100, 180); private Color gridColor = new Color(200, 200, 200, 200); private static final Stroke GRAPH_STROKE = new BasicStroke(2f); private int pointWidth = 4; private int numberYDivisions = 10; private List<Double> scores; public GraphPanel(List<Double> scores) { this.scores = scores; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); double xScale = ((double) getWidth() - (2 * padding) - labelPadding) / (scores.size() - 1); double yScale = ((double) getHeight() - 2 * padding - labelPadding) / (getMaxScore() - getMinScore()); List<Point> graphPoints = new ArrayList<>(); for (int i = 0; i < scores.size(); i++) { int x1 = (int) (i * xScale + padding + labelPadding); int y1 = (int) ((getMaxScore() - scores.get(i)) * yScale + padding); graphPoints.add(new Point(x1, y1)); } // draw white background g2.setColor(Color.WHITE); g2.fillRect(padding + labelPadding, padding, getWidth() - (2 * padding) - labelPadding, getHeight() - 2 * padding - labelPadding); g2.setColor(Color.BLACK); // create hatch marks and grid lines for y axis. for (int i = 0; i < numberYDivisions + 1; i++) { int x0 = padding + labelPadding; int x1 = pointWidth + padding + labelPadding; int y0 = getHeight() - ((i * (getHeight() - padding * 2 - labelPadding)) / numberYDivisions + padding + labelPadding); int y1 = y0; if (scores.size() > 0) { g2.setColor(gridColor); g2.drawLine(padding + labelPadding + 1 + pointWidth, y0, getWidth() - padding, y1); g2.setColor(Color.BLACK); String yLabel = ((int) ((getMinScore() + (getMaxScore() - getMinScore()) * ((i * 1.0) / numberYDivisions)) * 100)) / 100.0 + ""; FontMetrics metrics = g2.getFontMetrics(); int labelWidth = metrics.stringWidth(yLabel); g2.drawString(yLabel, x0 - labelWidth - 5, y0 + (metrics.getHeight() / 2) - 3); } g2.drawLine(x0, y0, x1, y1); } // and for x axis for (int i = 0; i < scores.size(); i++) { if (scores.size() > 1) { int x0 = i * (getWidth() - padding * 2 - labelPadding) / (scores.size() - 1) + padding + labelPadding; int x1 = x0; int y0 = getHeight() - padding - labelPadding; int y1 = y0 - pointWidth; if ((i % ((int) ((scores.size() / 20.0)) + 1)) == 0) { g2.setColor(gridColor); g2.drawLine(x0, getHeight() - padding - labelPadding - 1 - pointWidth, x1, padding); g2.setColor(Color.BLACK); String xLabel = i + ""; FontMetrics metrics = g2.getFontMetrics(); int labelWidth = metrics.stringWidth(xLabel); g2.drawString(xLabel, x0 - labelWidth / 2, y0 + metrics.getHeight() + 3); } g2.drawLine(x0, y0, x1, y1); } } // create x and y axes g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, padding + labelPadding, padding); g2.drawLine(padding + labelPadding, getHeight() - padding - labelPadding, getWidth() - padding, getHeight() - padding - labelPadding); Stroke oldStroke = g2.getStroke(); g2.setColor(lineColor); g2.setStroke(GRAPH_STROKE); for (int i = 0; i < graphPoints.size() - 1; i++) { int x1 = graphPoints.get(i).x; int y1 = graphPoints.get(i).y; int x2 = graphPoints.get(i + 1).x; int y2 = graphPoints.get(i + 1).y; g2.drawLine(x1, y1, x2, y2); } g2.setStroke(oldStroke); g2.setColor(pointColor); for (int i = 0; i < graphPoints.size(); i++) { int x = graphPoints.get(i).x - pointWidth / 2; int y = graphPoints.get(i).y - pointWidth / 2; int ovalW = pointWidth; int ovalH = pointWidth; g2.fillOval(x, y, ovalW, ovalH); } } // @Override // public Dimension getPreferredSize() { // return new Dimension(width, heigth); // } private double getMinScore() { double minScore = Double.MAX_VALUE; for (Double score : scores) { minScore = Math.min(minScore, score); } return minScore; } private double getMaxScore() { double maxScore = Double.MIN_VALUE; for (Double score : scores) { maxScore = Math.max(maxScore, score); } return maxScore; } public void setScores(List<Double> scores) { this.scores = scores; invalidate(); this.repaint(); } public List<Double> getScores() { return scores; } private static void createAndShowGui() { List<Double> scores = new ArrayList<>(); Random random = new Random(); int maxDataPoints = 40; int maxScore = 10; for (int i = 0; i < maxDataPoints; i++) { scores.add((double) random.nextDouble() * maxScore); // scores.add((double) i); } GraphPanel mainPanel = new GraphPanel(scores); mainPanel.setPreferredSize(new Dimension(800, 600)); JFrame frame = new JFrame("DrawGraph"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); } } It looks like this: A: Or simply use the JFreechart library - http://www.jfree.org/jfreechart/ .
[ "stackoverflow", "0000117101.txt" ]
Q: What is the best way to generate and print invoices in a .NET application? I'm working on a billing system for a utility company, and we have the following requirements: Batch-generate and print approximately 1,500 bills per day that we then mail to customers Save the bill in a format that can emailed to the customer and also archived (probably PDF) Built with .NET with MS SQL Server database back-end I'd like some advice about the best way to accomplish this. I'm thinking about building a WPF application that would have the bill template that we bind the bill data to and print from. But I haven't used WPF before so I'm not sure if that's the best technology to use, and I can't get my head around how the batching and PDF conversion would work. Any thoughts? Would WPF work, or is there a better solution? A: If you are using a SQL Server backend, Reporting Services should work for you. Otherwise I would recommend a third-party report generator that fits your reporting needs and create an app that uses it to create & export the reports.
[ "unix.stackexchange", "0000439980.txt" ]
Q: Syntax to update /etc/sudoers file What is the difference between the lines below. user1 ALL=(ALL) NOPASSWD: /etc/init.d/service-script user1 ALL=NOPASSWD:/etc/init.d/service-script Is both the lines correct and any difference ? I need to provide sudo access to user1 to execute the service script. A: First line has correct syntax. user1 ALL=(ALL) NOPASSWD: /etc/init.d/service-script It means: user1 can, on ALL hosts that use this /etc/sudoers file, become ALL users to run /etc/init.d/service-script without a password request. The second line has incorrect syntax, at least for modern versions of sudo. If you edited /etc/sudoers with the recommended visudo command, you would get a message similar to this after exiting your favorite editor: File /etc/sudoers.tmp saved >>> /etc/sudoers: syntax error near line 28 <<< What now? By typing a question mark, you would get a list of options: Options are: (e)dit sudoers file again e(x)it without saving changes to sudoers file (Q)uit and save changes to sudoers file (DANGER!) What now? It would be best to select either 'e' and remove the incorrect line, or 'x' to discard all edits you made this time. You might want to type a comment like this in your /etc/sudoers file to remind you of the correct syntax: # WHO WHERE = (AS WHOM) WHAT Between the (AS WHOM) and WHAT parts, you can optionally add a few colon-terminated tags that can affect some details of the procedure. Since the service-script is located in /etc/init.d, it apparently is intended to be run as root. So the "optimal" /etc/sudoers line would be: user1 ALL=(root) NOPASSWD: /etc/init.d/service-script The user should run it as: sudo /etc/init.d/service-script or explicitly sudo -u root /etc/init.d/service-script Adding arguments to the end of the command line is allowed.
[ "stackoverflow", "0030271390.txt" ]
Q: How do I navigate through a facebook $graphObject array and sort it So I've been playing around with the Facebook API and have found that it's not easy! It's very hard to get a grip of it all. So I've managed to get the users id, name, email, friends, movies, and music. /me?fields=id,name,email, friends.limit(5), movies.limit(5), music.limit(5) But I found that it doesn't actually return the most useful data. It will return the data in any random order. Which is annoying. I was wondering if there is a way to sort the Movies and Music based on the likes (Most likes to least likes)? At this stage all I've been able to do is print the users data using print_f($graphObject, 1). It would be really usefull if I could sort the Movies and Music based on the likes those pages have. I'll add my code so everyone can see where im upto with the FB api - As you'll see, not very far. But I want to get to know it a lot more. It's very useful! // start session session_start(); // init app with app id and secret FacebookSession::setDefaultApplication( 'App_ID','SECRET_KEY' ); // login helper with redirect_uri $helper = new FacebookRedirectLoginHelper( 'http://localhost/PHP_Advanced/Facebook/' ); // see if a existing session exists if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) { // create new session from saved access_token $session = new FacebookSession( $_SESSION['fb_token'] ); // validate the access_token to make sure it's still valid try { if ( !$session->validate() ) { $session = null; } } catch ( Exception $e ) { // catch any exceptions $session = null; } } if ( !isset( $session ) || $session === null ) { // no session exists try { $session = $helper->getSessionFromRedirect(); } catch( FacebookRequestException $ex ) { // When Facebook returns an error // handle this better in production code print_r( $ex ); } catch( Exception $ex ) { // When validation fails or other local issues // handle this better in production code print_r( $ex ); } } // see if we have a session if ( isset( $session ) ) { // save the session $_SESSION['fb_token'] = $session->getToken(); // create a session using saved token or the new one we generated at login $session = new FacebookSession( $session->getToken() ); // graph api request for user data $request = new FacebookRequest( $session, //Add permissions to this - All gets returned as json object 'GET', '/me?fields=id,name,email, friends.limit(5), movies.limit(5), music.limit(5)' ); $response = $request->execute(); // get response $graphObject = $response->getGraphObject()->asArray(); //Store basic user info to then put into database $userID = $graphObject['id']; $userName = $graphObject['name']; $userEmail = $graphObject['email']; echo "Hello ".$userName; echo "hello " . $data; // print profile data echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>'; // print logout url using session and redirect_uri (logout.php page should destroy the session) echo '<a href="' . $helper->getLogoutUrl( $session, 'http://localhost/PHP_Advanced/Facebook/' ) . '">Logout</a>'; } else { // show login url echo '<a href="' . $helper->getLoginUrl( array( 'email', 'user_friends','user_likes' ) ) . '">Login</a>'; } ?> </body> </html> A: Use {likes, name} to return likes count along with movie/music data. Eg: me?fields=id,name,email,movies.limit(5){likes,name},music.limit(5){likes,name} After that you can sort json data based on likes. Sample code: <?php $output = '{"id":"100004827362122","name":"FirstName LastName","email":"[email protected]","movies":{"data":[{"likes":725577,"name":"Canal D2M","id":"253861394671560"},{"likes":4514156,"name":"UTV Motion Pictures","id":"82457488277"},{"likes":48573,"name":"Unfreedom","id":"204640696244906"},{"likes":13677504,"name":"Star Wars","id":"263361123833008"},{"likes":246922,"name":"Shudh Desi Endings","id":"162737470589326"}],"paging":{"cursors":{"before":"MjUzODYxMzk0NjcxNTYw","after":"MTYyNzM3NDcwNTg5MzI2"},"next":"https://graph.facebook.com/v2.2/100004827362122/movies?pretty=0&fields=likes,name&limit=5&after=MTYyNzM3NDcwNTg5MzI2"}},"music":{"data":[{"likes":2215,"name":"WDL","id":"1472840169599887"},{"likes":113860,"name":"Daniel Waples - Hang in Balance","id":"161974437185126"},{"likes":229799,"name":"KEXP","id":"9054273111"},{"likes":1276105,"name":"The Movement","id":"253878101400547"},{"likes":13294164,"name":"Virgin Radio Lebanon","id":"275155342593810"}],"paging":{"cursors":{"before":"MTQ3Mjg0MDE2OTU5OTg4Nw==","after":"Mjc1MTU1MzQyNTkzODEw"},"next":"https://graph.facebook.com/v2.2/100004827362122/music?pretty=0&fields=likes,name&limit=5&after=Mjc1MTU1MzQyNTkzODEw"}}}'; $output = json_decode($output, true); $movies = $output['movies']['data']; function sortData($a, $b) { if ($a == $b) { return 0; } return ($a > $b) ? -1 : 1; } usort($movies, 'sortData'); echo "<pre>"; print_r($movies); ?>
[ "gaming.stackexchange", "0000263704.txt" ]
Q: How to defeat the Eye of Cthulhu How do I defeat the Eye of Cthulhu? I got him to half health with just a gun and a broadsword, but it became daytime. A: Prepare the terrain : Put a campfire (liferegen) Put a sunflower (movespeed) Build an area made of rows of wood platforms The fight Summon him @ 7:30pm Use piercing attack weapons Use a fast swinging weapon if swarmed Use the best armor you can afford Use potions (life, ironskin, thorns) You should also read this guide.
[ "stackoverflow", "0061110045.txt" ]
Q: How to add an extra field to the dataset in Vega-Lite My data set is an array of the following form: [ { "DATE" : "2020-01-02", "COUNTRY" : "Spain", "COUNT" : 110 }, { ... }, { ... } ] There are multiple countries and multiple days. There are no gaps in dates. I want to inject field DAYS_PASSED (and subsequently use it for the X axis) using the following algorithm: Check the value of DAYS_PASSED for the previous day for the same country and assign it to variable TEMP. (If the previous day does not exist, assume 0); Calculate DAYS_PASSED using the following formula: if TEMP > 0, then DAYS_PASSED = TEMP + 1 else-if COUNT > 100 then DAYS_PASSED = 1 else DAYS_PASSED = 0 So far I have done this in a preprocessing step (outside of Vega-Lite) but I was wondering if it was possible to migrate the calculation to Vega-Lite, maybe by plugging-in in a JavaScript function somehow? I would also like to be able to expose 100 (from the COUNT > 100 condition) in the graph so that the user can tweak it to, say, 200. A: You can do this with a series of transforms; for example: "transform": [ {"calculate": "toDate(datum.DATE)", "as": "date"}, {"calculate": "datum.COUNT < 100", "as": "pre100"}, { "joinaggregate": [{"op": "sum", "field": "pre100", "as": "offset"}], "groupby": ["COUNTRY"] }, { "window": [{"op": "count", "as": "daysPassed"}], "groupby": ["COUNTRY"], "sort": [{"field": "date"}] }, {"calculate": "max(0, datum.daysPassed - datum.offset)", "as": "daysPassed"} ], Here is a more full example showing this for a small dataset (vega editor): { "data": { "values": [ {"DATE": "2020-02-02", "COUNTRY": "Spain", "COUNT": 50}, {"DATE": "2020-02-03", "COUNTRY": "Spain", "COUNT": 70}, {"DATE": "2020-02-04", "COUNTRY": "Spain", "COUNT": 110}, {"DATE": "2020-02-05", "COUNTRY": "Spain", "COUNT": 150}, {"DATE": "2020-02-06", "COUNTRY": "Spain", "COUNT": 200}, {"DATE": "2020-02-02", "COUNTRY": "Italy", "COUNT": 90}, {"DATE": "2020-02-03", "COUNTRY": "Italy", "COUNT": 100}, {"DATE": "2020-02-04", "COUNTRY": "Italy", "COUNT": 140}, {"DATE": "2020-02-05", "COUNTRY": "Italy", "COUNT": 190}, {"DATE": "2020-02-06", "COUNTRY": "Italy", "COUNT": 250} ] }, "transform": [ {"calculate": "toDate(datum.DATE)", "as": "date"}, {"calculate": "datum.COUNT < 100", "as": "pre100"}, { "joinaggregate": [{"op": "sum", "field": "pre100", "as": "offset"}], "groupby": ["COUNTRY"] }, { "window": [{"op": "count", "as": "daysPassed"}], "groupby": ["COUNTRY"], "sort": [{"field": "date"}] }, {"calculate": "max(0, datum.daysPassed - datum.offset)", "as": "daysPassed"} ], "concat": [ { "mark": "line", "encoding": { "x": {"field": "DATE", "type": "temporal"}, "y": {"field": "COUNT", "type": "quantitative"}, "color": {"field": "COUNTRY", "type": "nominal"} } }, { "mark": "line", "transform": [{"filter": "datum.daysPassed > 0"}], "encoding": { "x": {"field": "daysPassed", "type": "quantitative"}, "y": {"field": "COUNT", "type": "quantitative"}, "color": {"field": "COUNTRY", "type": "nominal"} } } ] }
[ "stackoverflow", "0017929809.txt" ]
Q: EndRequest - Context.Response.StatusCode is always 200 (even when it should be 404) I'm trying to implement 404 handling as described here: https://stackoverflow.com/a/9026941/131809 In my EndRequest block, I have this: public class MvcApplication : HttpApplication { protected void Application_EndRequest() { if (Context.Response.StatusCode == 404) { //do stuff } } } However, the StatusCode always equals 200, even if I try to visit a url that definitely doesn't exist (/keyboardcat for example) The 'default' .net 404 page is still displayed however A: This only happened when using Cassini When switching to IIS, this was no longer that case
[ "stackoverflow", "0002078746.txt" ]
Q: Determine an value present in database sql php I've created a dynamic table that will pull information from a database. However, there is 1 field that may have NOTHING in it, or it may have a bunch of information (from multiple check boxes) in it. I am trying to condense the initial table view (the details will show full db field information). What I have right now is this: if $row['extras'] = ''{ print ''; } else { print 'Y'; By this code, it displays "Y" in ALL fields, rather than what is needs to. Am I on the right track or completely off base? A: think there's a typo, the code assigns (with one equals sign) rather than checks equality (2 equals signs)
[ "superuser", "0000989804.txt" ]
Q: Excel find and replace: prepend a number to all rows that contain bold numbers in a column I have an Excel workbook. One of the columns has numbers like 439857, 2139, 32, 5943, etc. Just random numbers. Some of them though have bold font style. I would like to prepend a single number, to all the numbers with bold font type in that column. Is that possible, and how? Example Original column: Column A 548976 434 5867 1845 7 468345 Desired result after find replace: Column A 2548976 2434 5867 21845 7 468345 2 was added to the front of bold numbers. A: Try this small macro: Sub dural() Dim r As Range, rng As Range Set rng = Intersect(ActiveSheet.UsedRange, Range("A:A")) For Each r In rng If r.Value <> "" And r.Font.Bold = True Then r.Value = 2 & r.Value End If Next r End Sub Note that because we are looking at a Property of the Range object, this is a no-go for Conditional Formatting or Character formatting.
[ "stackoverflow", "0003379906.txt" ]
Q: Can someone explain how to setText from a static using my example? First I would like to say that I have only worked with java for 1 month now. This is probly a pretty simple question. I searched and the classic fruit example did not make any sense to me. I spent hours looking at it and trying to figure out how to apply this to make it work. It does not make any sense to me because everyone explains how to get and set a property with 2 lines of code and no structure statements. I would really appreciate a breakdown in how to talk to non-static from static. I would like to setText in text box in my OBD2nerForm class from a separate and static class. public class OBD2nerForm extends java.awt.Frame { /** Creates new form OBD2nerForm */ public OBD2nerForm() { initComponents(); } .................................... public String setText(String text){ this.jFormattedTextField1.setText(text); } I think I have a static reference to this instance of the form defined here.. public class Status { public static OBD2nerForm form = new OBD2nerForm(); it is called from my main like this public class obd2ner { public static void main(String[] args) throws IOException { Status.form.main(args); Then when I try to call it.. Status.form.getText gives me the initial values when the form is created. When I setText, it does not change the one on the screen. I am just displaying this to keep it simple. There are many other parts going on. I have a static monitor on a serial port and I want it to grab the next data to be sent from the text box and then increment it. I just don't understand how to use a getter and a setter on a non-static. It's not quite doing what I need it to do. It seems like I am seeing one instance on my screen and it is using a new instance to perform the getting and setting. I tried this as per an answer I received, but it did not work... public class OBD2nerForm extends java.awt.Frame { String X = ""; //Trying out the runnable method of incrementing the code public String getNewScannerValueRunnable(){ Runnable doWorkRunnable = new Runnable() { @Override public void run() { Status.form.getNewRotatingValue() ;} }; SwingUtilities.invokeAndWait(doWorkRunnable); return X; } I could really use some other suggestions. i just don't understand what has to happen here. A: Your form is being created fine, and there's just one reference to it, and it's ending up in that static variable. All is well up to that point. There's a 'secret' of Swing you need to be aware of: You cannot (visibly) change the properties of GUI objects from any thread other than the Swing thread, aka the Event Dispatching Thread. The trick to doing it anyway is to pass the property-changing code as a Runnable to either of SwingUtilities.invokeAndWait() or SwingUtilities.invokeLater(). EDIT: OK, let's back up. Your form is AWT based, not Swing based, so I'm afraid my advice on using SwingUtilities would probably not have helped you, even if you had implemented it correctly. I'll try to give more specific hints this time. You've created a class OBD2nerForm that's an AWT form. That class has a constructor which calls initComponents to set up some GUI components on the screen. The class also has a method called setText that will put its argument text into one of the fields on the form. That method is an instance method, i.e. it's not "static", as you'd call it. You have another class, Status with a class field form. The initializer for form calls the constructor for OBD2nerForm. That will create an instance of the form and store it in form; but I haven't seen a show() or setVisible() call being made to the form to actually display it. Here are the first signs of trouble: public class obd2ner { public static void main(String[] args) throws IOException { Status.form.main(args); Class names (like obd2ner) should start with capital letters; but that's a matter of style and convention, it's not what's causing you problems. Following the conventions helps other people read and debug your code, though. The bigger problem is obd2ner.main() calling your form's main(). That could be made to work, but it's usually a sign that you're doing something wrong. While nothing stops you from coding static main methods into as many of your classes as you want, only one of those main's can be started from the outside, i.e. when you run your application. The first main is essentially the 'boss' method for your program. The "first main" usually instantiates and initializes a few objects. In a non-GUI application, main() may then start up a loop or some other control structure, wherein it will then orchestrate the actions of the other objects. In a GUI application, main() will usually just instantiate and then show the GUI, and then end; once the GUI is visible, all further program activity is triggered by actions the user performs on the GUI. Without seeing your code, I'm guessing that Obd2nerForm.main() also instantiates Obd2nerForm, and shows it. So you probably indeed have one instantiated but invisible form hanging off Status.form and another one instantiated, visible and referenced from some variable in Obd2nerForm. If you want to influence that GUI, you need to make a reference to that form accessible. Probably the simplest would be: In Obd2nerForm, declare a public static Obd2nerForm form, and in Obd2nerForm.main, right after you call the constructor, copy the reference to the form into that variable. From then on, you can access the form and its methods using e.g. Obd2nerForm.form.setText(). A reminder, though: You seem to have two main()s, and this needs fixing. All the stuff that should be done at the beginning of the app's lifetime needs to be in one of those mains, not several. Finally, look at this method call: Status.form.main(args); That's the syntax for calling a method on a particular instance. But Obd2nerForm.main is a class method (what you call "static"), and so there isn't "a particular one" to call, it's always just the one that belongs to the class itself. That's why the syntax to call a class method is something like Obd2nerForm.main(args); The compiler lets you get away with the way you wrote it, but it's not how it's usually done, and indicates some confusion. There... I hope that gets you a little further along. If you still have problems, please post a more complete code sample to PasteBin and I'll take a look!
[ "math.stackexchange", "0001716923.txt" ]
Q: if monic polynomial divides product, then it must divide at least one of them Suppose $F$ is a field and let $c \in F$. say $f(x),g(x) \in F[x]$. IF $x-c$ divides $f(x)g(x)$, then $x-c$ divides at least one of $f(x)$ or $g(x)$. try We know that can find unique $q_i(x) \in F[x]$ and unique $r_i \in F$ such that $f(x) = (x-c)p_1 + r_1$ and $g(x) = (x-c)p_2 + r_2$. So, $$ fg(x) = (x-c)( (x-c)p_1p_2 + p_1r_2 + p_2r_1) + r_1r_2 $$ since $x-c$ divides $fg$, then it must divide $r_1r_2$ but, then here I am stuck. I dont know how to procced from here. Any help? is my approach so good so far? A: Hint: If $x-c$ divides $f(x)g(x)$ then $c$ is a root of $f(x)g(x)$. So $f(c)g(c)=0$ and consequently $f(c)=0$ or $g(c)=0$.
[ "mathoverflow", "0000179873.txt" ]
Q: Group structure on an arbitrary completely regular topological space that makes $(x,y)\mapsto xy^{-1}$ continuous at $(1,1)$ Let $(G,\mathcal T)$ be a completely regular topological space. Is there a group structure on $G$ such that the function $$f:G\times G\to G$$ $$f(x,y)=xy^{-1}$$ is continuous at $(1,1)$? A: Here is a partial positive answer, going in the opposite direction of Terry´s comment. Let $X$ be an infinite topological space. Suppose $X$ is first countable at $p \in X$ and for every open neighborhood $U$ of $p$ there is a smaller neighborhood $V \subseteq U$ such that $|U \setminus V|=|U|$. Then there is a group structure on $X$ with identity $p$ such that the operation $(x,y) \mapsto xy^{-1}$ is continuous at $(p,p)$. Just note that (starting with a $U_0$ of minimal cardinality) we can find $\{U_n : n \in \omega\}$ an open local base at $p$ such that for every $n \in \omega$ we have $U_{n+1} \subset U_n$ and $|U_n \setminus U_{n+1}|=|U_0|$. Now find (e.g. using compactness of first-order logic) a group $G$ containing subgroups $H_0 \supset H_1 \supset H_2 \supset \cdots$, such that $|G|=|X|$ and $|H_n \setminus H_{n+1}|=|H_0|=|U_0|$ for every $n \in \omega$, and then transfer the group structure to $X$ in the obvious way. Note that we can also change the hypothesis to: there is an open neighborhood of $p$ with no smaller neighborhoods (e.g. $p$ is isolated) and the conclusion still holds; just call $U_0$ such neighborhood, find $G$ and $H_0$ as before and ignore the rest. Edit (Some details as to why such $G$ exists): Let $\kappa=|X|$ and $\mu=|U_0|$. Consider the language of first order logic consisting of a binary function symbol (for the group operation), countably many unary predicate symbols $\{P_n : n \in \omega\}$ and constant symbols $\{c^n_\alpha : \alpha \in \mu, n \in \omega\}$. In this language consider the first order theory that includes the group axioms, for each $n$ the axioms saying that $P_n$ is a subgroup and $P_{n+1} \subseteq P_n$, axioms saying that all the $c^n_\alpha$'s are distinct and $c^n_\alpha \in P_{n} \setminus P_{n+1}$. This theory is consistent because each finite fragment of it can be satisfied, e.g. using $\mathbb{Z}$ and finitely many of its subgroups. Since the language has size $\mu$, there is (by Lowenheim-Skolem) a model for this theory of size $\mu$. Inside this model we can find our $H_n$´s as the interpretations of the $P_n$'s. Finally we let $G=H_0 \times K$ where $K$ is any group of size $\kappa$.
[ "stackoverflow", "0022180484.txt" ]
Q: How to pass empty parameter through $_POST In one of the cakePHP framework's view, I take the parameters given by a user and make an action call. Here is how it looks like: echo $this->Html->link(__('Save as PDF'),array('action'=>'view_as_pdf',$_POST['data']['Event']['employee'],$_POST['data']['Event']['project'],$_POST['data']['Event']['from'],$_POST['data']['Event']['to'],'ext' => 'pdf')); The problem appears when *$_POST['data']['Event']['employee']* or *$_POST['data']['Event']['project']* project is not provided. That makes a proper url like: pdf.com/action/16/77/2014-01-01/2014-01-15 Look like: pdf.com/action/16/2014-01-01/2014-01-15 What I would like it to look is something like: pdf.com/action/16/null/2014-01-01/2014-01-15 A: Replace the items in your array passed into the link method with ternary operator and check the values. Essentially, you need to set a default value if the POSTed value is not set/empty/what-have-you. You could do something like this: empty($_POST['data']['Event']['project']) ? 'null' : $_POST['data']['Event']['project'] You need to pass a string of null in order for it to be passed as 'null'. Likely, the underlying code for that link method ignores empty parameters. Doing it this way will give you the pdf.com/action/16/null/2014-01-01/2014-01-15 url you are looking to achieve.
[ "stackoverflow", "0047268079.txt" ]
Q: Toggle that reveal text one at a time by click I have a problem with my code. The goal is to have a text that appear when a user click on the link. But I want also that when he clicks on the link the only text that show is the text underneath and not in all the cells. Can someone has a clue on what I did wrong? I will probable add other links (more than 2) and I want to be sure that it will work every time. $(document).ready(function() { $(".toggler").click(function(e) { e.preventDefault(); $('.cat' + $(this).attr('data-prod-cat')).toggle(); }); }); a { color: #002642; } .center { text-align: center; } .toggler, .cat1 { font-family: 'Varela Round'; color: white; } td { display: block; width: auto; border: 1px dotted #c4a77d; background-color: #c4a77d; color: white; margin-bottom: 10px; } @media only screen and (min-width: 70em) { td { display: table-cell; border: 1px dotted #c4a77d; background-color: #c4a77d; color: white; margin-bottom: 0px; } } p { font-family: 'Varela Round'; font-weight: bold; text-align: center; } <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <table cellpadding="0" cellspacing="5" style="table-layout: fixed; width:100%" width="100%"> <tbody> <tr> <td> <table style="width: 100%;text-align:center;"> <tbody> <tr> <td> <p>SOCIÉTÉS: 230</p> </td> </tr> <tr> <td><a class="toggler" data-prod-cat="1" href="#">+ En savoir plus</a></td> </tr> <tr class="cat1" style="display:none"> <td>Part CAC 40 : 40</td> </tr> <tr class="cat1" style="display:none"> <td>Part Filiales +100MK€: 190</td> </tr> </tbody> </table> </td> <td> <table style="width: 100%;text-align:center;"> <tbody> <tr> <td> <p>CONTACTS: 16 700</p> </td> </tr> <tr> <td><a class="toggler" data-prod-cat="1" href="#">+ En savoir plus</a></td> </tr> <tr class="cat1" style="display:none"> <td>Part CAC 40 : 10 000</td> </tr> <tr class="cat1" style="display:none"> <td>Part Filiales +100MK€: 6 700</td> </tr> </tbody> </table> </td> <td> <p>EMAIL NOMINATIF</p> </td> <td> <p>OPT OUT</p> </td> <td> <p>LIGNES DIRECTES/MOBILES</p> </td> </tr> </tbody> </table> A: You have just to go up to the parent table using closest('table') function and then select all the text's related to the current clicked .toggler using .find('[class^="cat"]') like : $(document).ready(function() { $(".toggler").click(function(e) { e.preventDefault(); $(this).closest('table').find('[class^="cat"]').toggle(); }); }); Hope this helps. $(document).ready(function() { $(".toggler").click(function(e) { e.preventDefault(); $(this).closest('table').find('[class^="cat"]').toggle(); }); }); a { color: #002642; } .center { text-align: center; } .toggler, .cat1 { font-family: 'Varela Round'; color: white; } td { display: block; width: auto; border: 1px dotted #c4a77d; background-color: #c4a77d; color: white; margin-bottom: 10px; } @media only screen and (min-width: 70em) { td { display: table-cell; border: 1px dotted #c4a77d; background-color: #c4a77d; color: white; margin-bottom: 0px; } } p { font-family: 'Varela Round'; font-weight: bold; text-align: center; } <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <table cellpadding="0" cellspacing="5" style="table-layout: fixed; width:100%" width="100%"> <tbody> <tr> <td> <table style="width: 100%;text-align:center;"> <tbody> <tr> <td> <p>SOCIÉTÉS: 230</p> </td> </tr> <tr> <td><a class="toggler" data-prod-cat="1" href="#">+ En savoir plus</a></td> </tr> <tr class="cat1" style="display:none"> <td>Part CAC 40 : 40</td> </tr> <tr class="cat1" style="display:none"> <td>Part Filiales +100MK€: 190</td> </tr> </tbody> </table> </td> <td> <table style="width: 100%;text-align:center;"> <tbody> <tr> <td> <p>CONTACTS: 16 700</p> </td> </tr> <tr> <td> <a class="toggler" data-prod-cat="1" href="#">+ En savoir plus</a></td> </tr> <tr class="cat1" style="display:none"> <td>Part CAC 40 : 10 000</td> </tr> <tr class="cat1" style="display:none"> <td>Part Filiales +100MK€: 6 700</td> </tr> </tbody> </table> </td> <td> <p>EMAIL NOMINATIF</p> </td> <td> <p>OPT OUT</p> </td> <td> <p>LIGNES DIRECTES/MOBILES</p> </td> </tr> </tbody> </table>
[ "stackoverflow", "0012551412.txt" ]
Q: JOIN statement not working with where clause I'm trying to do select * from buildings where levels = 3 join managers; but it says error at join. I want to match the the id of the building with the id in the managers table so I think I want natural join. A: If you put the JOIN in the right place (between FROM and WHERE) and it were legal to write JOIN without ON then the result would be a cross join - a cartesian product that you then filter in WHERE. That's a perfectly valid thing to do, though not probably what you intended in this case. It can be achieved by adding comma-separate tables to the FROM clause, eg: FROM buildings, managers It's generally better style to write an explicit inner join when you intend to join two tables on a condition: SELECT * FROM buildings b INNER JOIN managers m ON (b.manager_id = m.manager_id) WHERE b.levels = 3; ... because it makes it clear to someone else reading the statement that the ON clause is a join condition, and the bl.levels=3 is a filter. The SQL implementation generally doesn't care, and quite likely transforms the above into: SELECT * FROM buildings b, managers m WHERE b.levels = 3 AND b.manager_id = m.manager_id; internally anyway, but it's easier (IMO) to understand complex queries with many joins when they're written using explicit join syntax. There's another way to write what you want, but it's dangerous and IMO shouldn't be used: SELECT * FROM buildings bl NATURAL JOIN managers m WHERE bl.levels = 3; That JOINs on any columns that're named the same. It's a nightmare to debug, you have to look up the table structures to understand what it does, it breaks if someone renames a column, and it's just painful. Do not use. See Table expressions in the PostgreSQL manual. More acceptable is the USING syntax also discussed above: SELECT * FROM buildings bl INNER JOIN managers m USING (manager_id) WHERE bl.levels = 3; which matches the columns named manager_id in both columns and JOINs on them, combining them into a single column, but unlike NATURAL JOIN does so explicitly and without scary magic. I still prefer to write INNER JOIN ... ON (...) but it's reasonable to use USING and, IMO, never reasonable to use NATURAL. Test table structures were: create table managers ( manager_id integer primary key ); create table buildings ( manager_id integer references manager(manager_id), levels integer );
[ "stackoverflow", "0041137596.txt" ]
Q: How To Insert Incrementing Numbers with words by Multicursor in jetbrains IDE(IntelliJ IDEA)? I want to add Incrementing Numbers with words by Multicursor in jetbrains IDE(IntelliJ IDEA) . Is there any way to do it by Live template? I want to do things like this image : A: You could use String Manipulation plugin to do that (Increment/Decrement | Increment duplicate numbers). A: The plugin is not working on my WebStorm, there could be another way using unix command line: seq 1 10 | xargs printf 'string%d\n'
[ "stackoverflow", "0032213244.txt" ]
Q: pygame object wont move I have a very simple program. What I want is items in the thing class to move on their own. import pygame import time import random import threading #initilasies it pygame.init() #variables for height and width global display_width display_width= 800 global display_height display_height= 600 #declares colours uses RGB as reference white= (255,255,255) black = (0,0,0) #sets the dispaly (must be inside a tuple ()) gameDisplay = pygame.display.set_mode((display_width,display_height)) #changes the name of the window pygame.display.set_caption("Robot Quest") #times stuff (is gonna be used for FPS) clock = pygame.time.Clock() #loads up an image (not shown) must be in same directory tankImg = pygame.image.load("tank.png") blockImg = pygame.image.load("block.png") class things: def __init__(self,width,height,speed): self.width = width self.height = height #if display.width doesn't work just pass the screen dimensions self.X = display_width - self.width self.Y= display_height - self.height self.speed = speed def move(self): self.X -= self.speed pos = self.X return pos def drawImage(self,imageName,x,y): gameDisplay.blit(imageName,(x,y)) def game_loop(): #game exit value is set game_exit = False #when true you exit the loop, logic goes here while not game_exit: for event in pygame.event.get(): #method below on what to do if they press x in the corner if event.type == pygame.QUIT: #exit the loop pygame.quit() quit() #fills the background gameDisplay.fill(white) block = things(100,100,4) block.drawImage(blockImg,block.X,block.Y) block.move() pygame.display.update() clock.tick(30) game_loop() pygame.quit() quit() In the program block.move() executes once but that's all, so the object stays in the same place, having shifted only once place. I've tried to put the block.move() function in a for and while loop, but the program doesn't run if I do so. Can anyone advise me how fix my code so the object moves continuously, so it moves from end to the screen to another? A: You seem to initialize your block in each loop. Try moving block = things(100,100,4) to before the while loop.
[ "stackoverflow", "0048647252.txt" ]
Q: show splash screen while Webview is loading in background I'm using below code to populate my Main activity with Webview, but as it takes a certain time to load the page and it appears white blank. So I will like to show splash screen for my Webview before page load finishes. I'm not using any webview from Layout activity. package com.faraksoch.sagar.facebook; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; public class MainActivity extends Activity { private WebView mWebview = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); mWebview = new WebView(this); mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript final Activity activity = this; mWebview.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, int errorCode, String description, String failingUrl) { Toast.makeText(activity, description, Toast.LENGTH_SHORT).show(); } }); mWebview.loadUrl("http://www.google.com//"); setContentView(mWebview); } } I know that this code should work but I when I combine them..it won't work WebView wv = (WebView) findViewById(R.id.webView1); wv.getSettings().setJavaScriptEnabled(true); wv.setWebViewClient(new WebViewClient() { ... @Override public void onPageFinished(WebView view, String url) { //hide loading image findViewById(R.id.imageLoading1).setVisibility(View.GONE); //show webview findViewById(R.id.webView1).setVisibility(View.VISIBLE); } }); wv.loadUrl("http://yoururlhere.com"); Any help will be appreciated. Thanks in advance. A: Make sure webview is visibility is not GONE before it is loading. Please refer below code. public class WebViewActivity extends AppCompatActivity { private WebView mWebView; private ImageView mSplashView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web_view); mWebView = (WebView) findViewById(R.id.webview); mSplashView = (ImageView) findViewById(R.id.splash_view); mWebView.getSettings().setJavaScriptEnabled(true); // enable javascript mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); mSplashView.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); Toast.makeText(getBaseContext(), "Page Loaded.", Toast.LENGTH_SHORT).show(); } }); mWebView.loadUrl("http://yoururlhere.com"); mWebView.setVisibility(View.GONE); mSplashView.setVisibility(View.VISIBLE); } } Layout: <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="visible" /> <ImageView android:id="@+id/splash_view" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@mipmap/ic_launcher" android:visibility="gone" /> </android.support.constraint.ConstraintLayout>
[ "stackoverflow", "0004938556.txt" ]
Q: How do I control where an R plot is displayed, using python and rpy2? I'm writing a program in Python. The first thing that happens is a window is displayed (I'm using wxPython) that has some buttons and text. When the user performs some actions, a plot is displayed in its own window. This plot is made with R, using rpy2. The problem is that the plot usually pops up on top of the main window, so the user has to move the plot to see the main window again. This is a big problem for the user, because he's lazy and good-for-nothing. He wants the plot to simply appear somewhere else, so he can see the main window and the plot at the same time, without having to lift a finger. Two potential solutions to my problem are: (1) display the plot within a wxPython frame (which I think I could control the location of), or (2) be able to specify where on the screen the plot window appears. I can't figure out how to do either. A: Plot to a graphics file using jpeg(), png() or another device, then display that file on your wxWidget.
[ "stackoverflow", "0063192869.txt" ]
Q: Specify the right time to call a function inside a setInterval I am trying to write a loop that switches from red, green and blue, but when it reaches the 255 of a color, it turn black. I got stuck at the function change(), how can I specify to the function the exact time that it should call the inner functions (turnRed, turnGreen, turnBlue)? var r = 0; var g = 0; var b = 0; var dir = true; function turnRed(){ if (dir == true){ r < 256 ? r++ : 0; if (r == 255){ dir = false; }else{ turnBlack; } } } function turnGreen(){ if (dir == true){ g < 256 ? g++ : 0; if (g == 255){ dir = false; }else{ turnBlack; } } } function turnBlue(){ if (dir == true){ b < 256 ? b++ : 0; if (b == 255){ dir = false; } else{ turnBlack; } } } function turnBlack(){ b > 0 ? b-- : 0; if (b == 0){ dir = true; } g > 0 ? g-- : 0; if (g == 0){ dir = true; } r > 0 ? r-- : 0; if (r == 0){ dir = true; } } function change() { color = 'rgb('+r+', '+g+', '+b+')'; document.body.style.backgroundColor = color; setTimeout(turnRed, 1000); clearInterval(); //then setTimeout(turnGreen, 1000); clearInterval(); //then setTimeout(turnBlue, 1000); clearInterval(); } setInterval(change, 10); clearInterval(); My logic: if I put setTimeout(function, time) into a setInterval, it will call the function once, and setInterval will run in a loop changing the colors, but in my case the function just runs once and stops. A: Here is a working example. There were a few bugs in your code. You didn't have the () after turnBlack to actually call the function. I removed the g > 0 ? g-- : 0; since you change direction when it's needed and then it won't matter. I'm also not sure the setTimeouts are needed inside change. This just delays everything 1 second from happening. var r = 0; var g = 0; var b = 0; var dir = true; function turnRed(){ if (dir == true) { if (r < 256) { r++; } else { dir = false; } } else { turnBlack(); } } function turnGreen(){ if (dir == true) { if (g < 256) { g++; } else { dir = false; } } else { turnBlack(); } } function turnBlue(){ if (dir == true) { if (b < 256) { b++; } else { dir = false; } } else { turnBlack(); } } function turnBlack(){ if (b == 0){ dir = true; } else { b-- } if (g == 0){ dir = true; } else { g-- } if (r == 0){ dir = true; } else { r-- } } function change() { color = 'rgb('+r+', '+g+', '+b+')'; document.body.style.backgroundColor = color; setTimeout(turnRed, 1000); clearInterval(); setTimeout(turnBlue, 1000); clearInterval(); setTimeout(turnGreen, 1000); clearInterval(); } setInterval(change, 10); clearInterval(); Clear interval doesn't do anything unless you pass it an interval. But that would stop what you want. For example: var myVar = setInterval(myTimer, 1000); clearInterval(myVar) I think this will work fine. var r = 0; var g = 0; var b = 0; var dir = true; function turnRed(){ if (dir == true) { if (r < 256) { r++; } else { dir = false; } } else { turnBlack(); } } function turnGreen(){ if (dir == true) { if (g < 256) { g++; } else { dir = false; } } else { turnBlack(); } } function turnBlue(){ if (dir == true) { if (b < 256) { b++; } else { dir = false; } } else { turnBlack(); } } function turnBlack(){ if (b == 0){ dir = true; } else { b-- } if (g == 0){ dir = true; } else { g-- } if (r == 0){ dir = true; } else { r-- } } function change() { color = 'rgb('+r+', '+g+', '+b+')'; document.body.style.backgroundColor = color; turnRed(); turnBlue(); turnGreen(); } setInterval(change, 10); This changes colors individually. First to Red -> Black -> Green -> Black -> Blue -> Black var r = 0; var g = 0; var b = 0; var dir = 'red'; var nextColor = 'green' function turnRed(){ if (dir == 'red') { if (r < 256) { r++; } else { dir = 'black'; nextColor = 'green' } } } function turnGreen(){ if (dir == 'green') { if (g < 256) { g++; } else { dir = 'black'; nextColor = 'blue' } } } function turnBlue(){ if (dir == 'blue') { if (b < 256) { b++; } else { dir = 'black'; nextColor='red'; } } } function turnBlack(){ if (dir !== 'black') return; if (b > 0) b--; if (r > 0) r--; if (g > 0) g--; if (b <= 0 && r <= 0 && g <= 0) { dir = nextColor; } } function change() { color = 'rgb('+r+', '+g+', '+b+')'; document.body.style.backgroundColor = color; turnRed(); turnBlue(); turnGreen(); turnBlack() } setInterval(change, 10); Lastly this changes to Red, then decreases Red as it Increases Blue, and keeps doing that for all the colors. var r = 0; var g = 0; var b = 0; var dir = 'red'; var nextColor = 'green' function turnRed(){ if (dir == 'red') { if (r < 256) { r++; } else { dir = 'green' } } } function turnGreen(){ if (dir == 'green') { if (g < 256) { g++; } else { dir = 'blue' } } } function turnBlue(){ if (dir == 'blue') { if (b < 256) { b++; } else { dir = 'red'; } } } function turnBlack(){ if (b > 0 && dir !== 'blue') b--; if (r > 0 && dir !== 'red') r--; if (g > 0 && dir !== 'green') g--; } function change() { color = 'rgb('+r+', '+g+', '+b+')'; document.body.style.backgroundColor = color; turnRed(); turnBlue(); turnGreen(); turnBlack(); } setInterval(change, 10);
[ "superuser", "0000410710.txt" ]
Q: How to change the folder Outlook 2010 saves sent emails to? How to change the folder Outlook 2010 saves sent emails to? I want a custom one, because I want to use my account from two different clients - Outlook 2010 and Thunderbird. A: Rules on outgoing messages always run client-side, never on the server, so you are looking at two separate solutions for the Outlook 2010 and Thunderbird clients. You will need to create rules in both mail-clients that will forward a copy of all outgoing mail to the new Saved-Sent folder, which will probably also require a server-side rule to get these forwards to the right folder. For Thunderbird, maybe the Send Filter add-on can help. For outlook, Create a rule to file our outgoing emails might help. (As I don't use Exchange or Outlook, I can't help with the details.)
[ "math.stackexchange", "0002445562.txt" ]
Q: Is the unit group of any finitely generated reduced $\Bbb Z$ algebra finitely generated? If $A$ is finitely generated commutative reduced $\Bbb Z$ algebra, must the unit group $A^{\times}$ be finitely generated? The question is motivated by the Dirichlet unit theorem which says the unit group of the algebraic integer ring of any number field is finitely generated. And for other $\Bbb Z$ algebras such as finite fields, their unit groups are even finite. A: "I think the case that $A$ is finite as $\mathbf Z$-module is always true". Yes, it's true, it's even presented as "a generalization of the unit theorem" in §4.7 of P. Samuel's booklet on ANT. The particular case that $A$ is an integer domain is easy, because then, as you said, $A$ would be an order of some number field in characteristic $0$, or $A$ would be finite in non zero characteristic. But what worries me is your hint (which I can't quite grasp) at the finite number of minimal primes of $A$ to reduce to that particular case, whereas Samuel feels obliged to go on with a technical inductive proof on the nilradical $N$ of $A$. More precisely, the induction bears on the exponent $s$ such that $N^s = (0)$. The starting step is $s=0$, i.e. $A$ is a reduced ring in which ($0$) is the intersection of finitely many prime ideals $P_i$'s, and so $A^*$ injects into the direct product of the $(A/P_i)^*$'s, which are of finite type according to the particular case. Next assume $s>1$ and consider the natural map $\phi : A \to A/N^{s-1}$. By the induction hypothesis $\operatorname{Im}\phi$ is finitely generated, and Samuel shows that $\ker\phi = 1+N^{s-1}$ and that the latter group is finitely generated. Finally, your original question, with the additional assumption that $A$ is reduced, has an affirmative answer, see P. Samuel, "A propos du théorème des unités", Bull. Sc. Math., 90 (1966), 89-96).
[ "superuser", "0000212260.txt" ]
Q: Need to convert/import Lotus Notes Knowledge Base Document Repository Helpdesk Database I have a Lotus Notes Database that is a knowledge base for a helpdesk function. We no longer have a Notes environment, nor even a copy of Lotus Notes to stick on a machine and run. I have kept a copy of the database but now need to convert it or import it into another format to run the same. We have Sharepoint Portal server 2003 and Sharepoint 2010 Foundation so if it could be converted into that it would be ideal, we also have SQL Server 2005. I do not know SQL so the database was a really quick way for someone with no SQL knowledge to setup and just go. Cost is a factor in this and if it costs any money to convert/import this I will need to setup from scratch. Any help appreciated. A: With the lack of response I'm guessing there is no way of doing it without a cost of migration to an alternative system. Closing Question As No solution.
[ "stackoverflow", "0032736458.txt" ]
Q: How to use TI Sensortag on Windows Desktop with USB 4.0 BLE Dongle I have an Asus USB-BT400 Bluetooth Dongle, it works with BLE devices. I also have an TI Sensortag, i installed the drivers and software and I can connect my PC to the sensortag (using windows 7 or windows 8.1 in VM, both works). Windows doesn't find drivers for the sensors (I think 8 in total) so I would like to know how I can communicate to them. I already exposed a COM port for the bluetooth device (that's possible via Bluetooth settings). I tried the BLE device monitor, where the COM port shows up, but it gives an error (no response from BLE host at port COM3). I also tried the windows Desktop app (win8), which doesn't work either. I would be glad for any solutions, resources and hints which do not require me to buy the Dongle from TI website for ~50$. Thank you! A: I don't believe it works under anything less than Win 8.1 as the OS must have the BLE Profile drivers. Running VM is not going to help, as you need those drivers at the base OS level.
[ "stackoverflow", "0033386318.txt" ]
Q: How to fix my Background solution to make thread-safe calls? I tried to set Text property of TextBox from another thread. I got this exception below; "Cross-thread operation not valid: Control 'recTpcTxt' accessed from a thread other than the thread it was created on." Then, I used BackgroundWorker to solve this issue. However, I faced with the same exception message. EDIT[1]: Actually, I take a guide myself this link ; https://msdn.microsoft.com/en-us/library/ms171728(v=vs.110).aspx. I can solve my problem by using invokeproperty. However, I cannot solve my problem with backgroundworker. Is there something wrong in my solution? How do I fix my solution to set some property of UI variable? EDIT[2]: More code to clarify the issue; MqttManager.cs; public partial class MqttManager : Form { MqttHandler mqttHandler = new MqttHandler(); public static MqttManager managerInst; public MqttManager() { InitializeComponent(); managerInst = this; ... } ... private BackgroundWorker backgroundWorker; public void NotifyUIForRecMsg(string topic, string message) { object[] objArr = { topic, message }; this.backgroundWorker.RunWorkerAsync(objArr); } private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { System.Threading.Thread.Sleep(5000); e.Result = e.Argument; } private void backgroundWorker_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { object[] res = (object[])e.Result; this.recTpcTxt.Text = (String)res[0]; } } MqttManager.Design.cs; partial class MqttManager { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { ... this.backgroundWorker = new System.ComponentModel.BackgroundWorker(); this.backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker_DoWork); this.backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker_RunWorkerCompleted); } #endregion ... } MqttHandler.cs; class MqttHandler { MqttClient client; ... /// <summary> /// Publish received event handler. /// </summary> private void client_MqttMsgPublishReceived(Object sender, MqttMsgPublishEventArgs e) { MqttManager.managerInst.NotifyUIForRecMsg(e.Topic, Encoding.UTF8.GetString(e.Message)); } } A: check this: https://msdn.microsoft.com/en-us/library/ms171728(v=vs.110).aspx Basically, to set a control propertiy you have to be in the same UI thread. This simple solution move the call to textbox1.Text = someText in the UI thread private void SetText(string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; } } also, you can use textBox1.BeginInvoke instead of Invoke: it will run in UI thread, without locking the caller thread waiting for SetText delegate to be completed [Edit] to do it in your backgroundWorker: private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { object[] arg = (object[])e.Argument; SetTextToTextBox(recTpcTxt, (string)arg[0]); SetTextToTextBox(recMsgTxt, (string)arg[1]); } private void SetTextToTextBox(TextBox toSet, string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (toSet.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); toSet.Invoke(d, new object[] { text }); } else { toSet.Text = text; } } [Edit 2] To properly use backgroundworker Register for events DoWork and RunWorkerCompleted this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork); this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted); Before exiting backgroundWorker1_DoWork, set result property of eventArgs, and read them in backgroundWorker1_RunWorkerCompleted private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { System.Threading.Thread.Sleep(5000); e.Result = new string[] { "one", "two" }; } private void backgroundWorker1_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { string[] res = (string[])e.Result; this.textBox1.Text = res[0]; }
[ "webmasters.stackexchange", "0000042917.txt" ]
Q: why isn't mozilla rendering my custom fonts I working on a website - goodmorninghomes.com The site looks perfect in all browsers including internet explorer but not in mozilla and the problem is the different fonts. I have included some custom fonts through @font-face CSS property and they are working properly in all browsers but not in firefox. The firefox console doesnt even show any problem. I just cant understand why this is happening. A: Your find that neither Chrome or Firefox is rendering Ambient via the @Font-Face and what is happening is that the Crusive Font is rendering slightly different in Firefox than Chrome (Very Little Difference, but its using Crusive not Ambient, Fix posted below) Chrome, and Firefox render fonts differently from one another so sometimes you notice no change, little change or sometimes noticeable change. The font that is being used is Cursive and not Ambient because this is not setup right. IN THE HTML <div class="grid_6" id="call">Call: 099 XX XX XX XX</div> IN THE CSS FOR THIS ELEMENT #call { font-size: 18px; color: #a27780; font-family: ambient, sans-serif; } ** IN THE CSS FOR @FACE @font-face { font-family: 'ambientmedium'; src: url('ambient-webfont.ttf') format('truetype'); font-weight: normal; font-style: normal; } Now if you pay attention and take a look at the @Font-Face for a second your notice that it uses the font-family 'ambientmedium' yet you are calling up on the font-family: ambient. Change your FONT-FAMILY IN THE CSS FROM #call { font-size: 18px; color: #a27780; font-family: ambient, sans-serif; } TO #call { font-size: 18px; color: #a27780; font-family: ambientmedium, sans-serif; } ADDITIONALLY You should consider using better FONT Compatibility, Your currently limiting your site to browsers than understand TTF there are versions and different browsers that can't work with TTF. You you add additional fonts to allow maximum compatibility - You want to use ttf, of, svg and woff. You can convert your fonts here: http://www.font2web.com/ Furthermore and finally this question is more suitable for Stack OverFlow ;)
[ "stackoverflow", "0023933342.txt" ]
Q: How to get properties from a xml response coming from a Rest call I am using rest-client-builder:2.0.1 plugin in grails. I am calling a rest url with a xml response and I am getting back a xml response also. Here is my rest call, def url = "http://ab-rest/getDetails" def xmlBody = "<someGrp><id>CAP00001-1</id><Name>XX642105YP</Name>" xmlBody = xmlBody+"<Grade>1</Grade><AccessCode></AccessCode>" xmlBody = xmlBody+"<productCode>ABC</productCode>" xmlBody = xmlBody+"<imageuri>www.abcd.com/232134</imageuri></imageuris><someGrp>" log.debug "image processor xmlBody: ${xmlBody}" def resp = rest.post(url) { header "Content-Type", "application/xml" header "X-Requested-With", "XMLHttpRequest" header "X-LTCallingApplicationName", "ABC" header "X-LTCallingUser", "TEST" header "X-LTCallingApplicationInstance", "System" header "X-LTCallingApplicationId", "70" xml xmlBody } resp.xml instanceof GPathResult log.debug " resp.status "+resp.status log.debug "image processor response xml: ${resp.xml}" If I do resp.status here it returns 200 but response.xml just returns the property values in a concatenated form. Like below, ID01-1CAP01-1http://qa.imagecache.cir.lifetouch.net/imagecache/service/imagecache/didimage/bd56a1783eb32b88a31964888cbba066d58961a4200jpg But expected xml was, <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <images> <image> <id>ID01-1</id> <capturesession>CAP01-1</capturesession> <uri>http://ab-rest.net/imagecache/didimage/bd56a1783eb32b88a31964888cbba066d58961a4</uri> <status>200</status> <filetype>jpg</filetype> </image> </images> When I do a resp.text I get the below in as a string, <?xml version="1.0" encoding="UTF-8" standalone="yes"?><images><image><id>ID01-1</id><capturesession>CAP01-1</capturesession><uri>http://ab-rest.net/imagecache/didimage/bd56a1783eb32b88a31964888cbba066d58961a4</uri><status>200</status><filetype>jpg</filetype></image></images> Now I want to get the properties from the response, like if I wantto get the uri how to do that? A: It return you a parsed xml, check the class and it will be a XmlSlurper. e.g. resp.xml.image.find { log.debug it.uri }
[ "stackoverflow", "0003359714.txt" ]
Q: Weird iAd Error causing crash I'm getting a very strange crash due to iAd. Here's the debugger output: 2010-07-29 17:25:57.032 MemoryMatcherFree[5326:307] -[__NSOperationInternal bannerViewDidLoadAd:]: unrecognized selector sent to instance 0x13fda0 2010-07-29 17:25:57.051 MemoryMatcherFree[5326:307] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSOperationInternal bannerViewDidLoadAd:]: unrecognized selector sent to instance 0x13fda0' *** Call stack at first throw: ( 0 CoreFoundation 0x3513cfd3 __exceptionPreprocess + 114 1 libobjc.A.dylib 0x303928a5 objc_exception_throw + 24 2 CoreFoundation 0x35140a77 -[NSObject(NSObject) doesNotRecognizeSelector:] + 102 3 CoreFoundation 0x3513ff15 ___forwarding___ + 508 4 CoreFoundation 0x350d2680 _CF_forwarding_prep_0 + 48 5 iAd 0x30fe70c7 -[ADBannerView transitionToNextBanner:] + 1230 6 iAd 0x30fe69b7 -[ADBannerView _adManagerLoadedBannerData:] + 314 7 iAd 0x30fddf13 -[ADCache _notifySuccess] + 358 8 iAd 0x30fde25f -[ADCache _dispatchResponses] + 50 9 Foundation 0x339ccbd9 __NSFireTimer + 136 10 CoreFoundation 0x35112a5b __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 14 11 CoreFoundation 0x35114ee5 __CFRunLoopDoTimer + 860 12 CoreFoundation 0x35115865 __CFRunLoopRun + 1088 13 CoreFoundation 0x350be8eb CFRunLoopRunSpecific + 230 14 CoreFoundation 0x350be7f3 CFRunLoopRunInMode + 58 15 GraphicsServices 0x309776ef GSEventRunModal + 114 16 GraphicsServices 0x3097779b GSEventRun + 62 17 UIKit 0x321c12a7 -[UIApplication _run] + 402 18 UIKit 0x321bfe17 UIApplicationMain + 670 19 MemoryMatcherFree 0x00002b77 main + 70 20 MemoryMatcherFree 0x00002b2c start + 40 ) terminate called after throwing an instance of 'NSException' Program received signal: “SIGABRT”. Any ideas/things to try would be greatly appreciated. Cheers. A: Are you sure that you have released the bannerView's Delegate? I created a method called: "releaseBannerView". I did it this way so that I could "weak" link my iAd.framework, and only call the method if the iAd class was present. Works really well for backwards capability. -(void)releaseBannerView { //Test for the ADBannerView Class, 4.0+ only (iAd.framework "weak" link Referenced) Class iAdClassPresent = NSClassFromString(@"ADBannerView"); //If iOS has the ADBannerView class, then iAds = Okay: if (iAdClassPresent != nil) { //If instance of BannerView is Available: if (self.bannerView) { //Release the Delegate: bannerView.delegate = nil; //Release the bannerView: self.bannerView = nil; } } } Then when needed and inside my Dealloc method, I can just nil out the bannerView by calling this method: - (void)dealloc { [super dealloc]; [self releaseBannerView]; ..and.others... }
[ "gaming.stackexchange", "0000203339.txt" ]
Q: How do I update to Giraffe? How do I update my game to Upbeat Giraffe? I saw it recently came out, so I want to download it so me and my friend can continue playing. But, the game says it is up to date, despite while in game saying I am at Enraged Koala. Is there anyway to update the game files without deleted my local content? A: The update is now available and will download when you log into Steam, assuming you have automatic downloads on and are opted into Starbound's "stable branch".
[ "stackoverflow", "0019621569.txt" ]
Q: Rails make an STI backed form post to the correct path I am using STI in my rails app: class Project < ActiveRecord::Base end class Video < Project end I've got the following routes: resources :projects resources :videos, :controller => "projects", :type => "video" And when I rake my routes I see that I should be able to POST to /videos: POST /videos(.:format) projects#create {:type=>"video"} However, when I visit /videos/new, I notice that the form posts to /projects = form_for(@project) do |f| ... creates the following HTML ... <form action="/projects" method="post" > <!-- ommited --> </form My new action in projects_controller looks like this: def new @project = params[:type].capitalize.constantize.new end def create @project = params[:type].capitalize.contstantize.new(project_params) end I want it to post to /videos and not /projects, because params[:type] is always set to "video" when we are on urls that start with /videos, whereas it's not set to anyything when we are on urls that start with /projects. UPDATE: I have a temporary fix: = f.hidden_field :type Does the trick when url changes to /projects, but I'd rather have the form post to /videos... A: I've flagged the question for deletion because I had the following in my code: def self.inherited(child) child.instance_eval do def model_name Project.model_name end end super end After removing that, everything works just the way I want it to. Whoops. Sorry!
[ "stackoverflow", "0059286265.txt" ]
Q: How to inject a service into another service and use it within exported constants or interfaces in Angular? I would like to inject a service into another service with which I want to translate strings within exported constants. My code currently looks like this (I've simplified it here) // Imports.. @Injectable( { providedIn: 'root' } ) export class MyService { constructor(private httpClient: HttpClient, private injectedService: InjectedService) { } // Methods.. } export enum Series { prop_1 = 'String_1', prop_2 = 'String_2', prop_3 = 'String_3', } export const ALL_SERIES: Series[] = [ this.injectedService.translate(Series.prop_1), this.injectedService.translate(Series.prop_1), this.injectedService.translate(Series.prop_1), ]; However, I get this error because the injected service is not detected outside the component: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'injectedService' of undefined What would be the cleanest solution to this problem? A: You could simply create a getSeries method in the service that will return the values of the constant. This will be defined inside the MyService class and thus no error. @Injectable({ providedIn: 'root' }) export class MyService { constructor(private httpClient: HttpClient, private injectedService: InjectedService) {} // Methods.. getSeries(): Series[] { return [ this.injectedService.translate(Series.prop_1), this.injectedService.translate(Series.prop_1), this.injectedService.translate(Series.prop_1), ]; } } export enum Series { prop_1 = 'String_1', prop_2 = 'String_2', prop_3 = 'String_3', } Instead of ALL_SERIES you would have to call getSeries() method though.
[ "stackoverflow", "0017512869.txt" ]
Q: Javascript (object.innerhtml) is not compatible with IE I have created a script that changes the combo boxes based on the category chosen. The problem is that the script works in all other browsers aside from Internet Explorer (version 7+). I am not getting an error message, which indicates that IE doesn't like the object.innerhtml. What can I do to solve this? Working Example: http://adcabinetsales.com/style-chooser.html function ChangeCabinetCollection() { if (document.getElementById("cabinet_collection").value == "broughton") { // COPY VALUES var first = document.getElementById('broughton_styles'); var options = first.innerHTML; var second = document.getElementById('cabinet_selector'); // REPLACE VALUES second.innerHTML = options; // CHANGE CABINET IMAGE TO BE IN THE COLLECTION OF CHOICE changeDoor("cabinet_selector"); } else if (document.getElementById("cabinet_collection").value == "specialty") { // COPY VALUES var first = document.getElementById('cabinet_style'); var options = first.innerHTML; var second = document.getElementById('cabinet_selector'); // REPLACE VALUES second.innerHTML = options; // CHANGE CABINET IMAGE TO BE IN THE COLLECTION OF CHOICE changeDoor("cabinet_selector"); } } function ChangeGraniteCollection() { if (document.getElementById("granite_collection").value == "new_arrivals") { // COPY VALUES var first = document.getElementById('granite_new'); var options = first.innerHTML; var second = document.getElementById('granite_selector'); // REPLACE VALUES second.innerHTML = options; // CHANGE CABINET IMAGE TO BE IN THE COLLECTION OF CHOICE changeGranite("granite_selector"); } else if (document.getElementById("granite_collection").value == "Specialty Styles") { // COPY VALUES var first = document.getElementById('specialty_granite_styles'); var options = first.innerHTML; var second = document.getElementById('granite_selector'); // REPLACE VALUES second.innerHTML = options; // CHANGE CABINET IMAGE TO BE IN THE COLLECTION OF CHOICE changeGranite("granite_selector"); } } A: It's not .innerHTML in general; it's using it with <select> elements that's causing you problems. There are a couple ways to solve the problem. A simple one is to replace the entire <select> element along with the option list. That is, if your HTML looks like this: <select name=whatever id=whatever> <option value=1>Hello <option value=2>World </select> Then you could alter that to be: <span class=select-wrapper> <select name=whatever id=whatever> <option value=1>Hello <option value=2>World </select> </span> Then just replace the .innerHTML of the <span> wrapper around the <select>. The other way to solve the problem is to build an array of Option instances and update the "options" property of the <select> element.
[ "serverfault", "0000340865.txt" ]
Q: SSH tunnel over multi hops using putty I have a situation where I want to connect to a Linux machine running VNC (lets call it VNCServer) which is behind two consecutive Linux machines i.e., to ssh into the VNCServer, I have to ssh into Gateway1 from my laptop, then from Gateway1 shell I ssh into the Gateway2 and then from that shell I finally ssh into VNCServer. I cannot change the network design and access flow Laptop-->Gateway1-->Gateway2-->Server. I have no root privileges on Gateway1 and all ports except 22 and 5901 are closed. Is there a way by which I can launch a VNC viewer on my laptop and access the VNCServer? I understand that it might be done using ssh tunneling features and I have putty on my Windows laptop (sorry, no Linux or Cygwin etc. can be installed on the work laptop). Any help will be greatly appreciated as this would make my life so easier! A: Putty does support ssh tunnels, if you expand the Connection, SSH tree, you'll see an entry for tunnels. Local tunnels produce a localhost port opening on your windows machine that remotes to the ip address and port you specify. For instance, when I'm trying to RDP to a desktop at my house, I'll generally choose a random local port, something like 7789, then put the local ip address of the desktop (1.2.3.4:3389) as the remote host. Be sure to click "Add", then "Apply." At this point, when you rdp to 127.0.0.1:7789, you'll then connect to 1.2.3.4:3389 over the putty session. This is where the fun comes in. If you then setup a port tunnel on your intermediate box, setting up the local port you specified as the remote port in putty, you can then bounce through your putty, through the intermediate box your final destination. You'll still need to do a few ssh connects, but you'll be able to cross vnc or rdp directly from the windows system once you're set, which is what I believe you're looking to do. EXAMPLE Head over to the tunnels panel in Putty (Connections->SSH->Tunnels accessed either from the context menu if the ssh session is already active, or in the beginning connection screen when just starting putty) Create a tunnel with local source 15900, and remote source 127.0.0.1:15900 Connect (if not already connected) to Gateway1. On Gateway1, ssh -L 127.0.0.1:15900:VNCServerIP:5900 user@Gateway2 Once the ssh to Gateway2 is up, attempt to vnc to 127.0.0.1:15900 -- you should now see the VNC screen on the far side! ADDED BONUS -- not many people know this, but this process can also be used to proxy IPv6/IPv4 traffic as well. SSH doesn't care what protocol it uses for the tunnels, so you can theoretically access IPv6 only hosts from an IPv4 only system, given that the ssh server is dual stack (has both IPv4 and IPv6 addresses.) A: There is an alternate if you want to use PuTTY for both hops. In this example we are hopping from Gateway #1 (10.0.1.123) to Gateway #2 (10.0.1.456) to port 80 on 10.0.1.789. First create hop to gateway #1. First setup the connection to the first server. Setup a tunnel to the second gateway in Connection>SSH>Tunnels. In this example we're forwarding port 2222 to the second gateway. Now we'll setup the second hop. We'll tunnel through the first gateway to the next gateway and setup port forwarding on the second gateway. The connection is to localhost on port 2222. This will tunnel through the running ssh connection to the second hop. On this connection we setup a port forward from port 3333 to 10.0.1.789. Now open up a browser and navigate to 127.0.0.1:3333 and you'll tunnel through the two SSH connections to 10.0.1.789:80
[ "stackoverflow", "0002165011.txt" ]
Q: Using OpenCV to detect a finger tip instead of a face I'm using the facedetect example and going from there. Right now it only detects faces. Could someone point me in the direction to detect finger tips. Thanks A: Put a simple bright fluorescent sticker on the finger tip with a black dot in center or something like that. or even fashion a finger cap with a pattern printed on it which can be easily differentiated by the camera and your problem is very much solved.
[ "sharepoint.stackexchange", "0000130862.txt" ]
Q: VS 2013, visual web part - "Design View" on *.ascx files does not work I have VS 2013 with last updates and service-pack. VS hangs, the window does not show design mode(remains in "view source"), then need to close/reopen tab with .ascx file. It is on all visual webparts, newly created too I suspect that there is some application conflict. A: In my case solution is - uninstall and reinstall VS(I suspect possibly the error was caused by CKS Addition).
[ "stackoverflow", "0016799877.txt" ]
Q: how can I disable manual inputs in the text input field- JQuery Datepicker I have a text box and I can able to find the ID of that textbox. Binded a JQuery date picker to that text box. My requirement is the user can select the values only through Datepicker. User can't enter value manually. Is it possible? Any help is very ppreciated! A: make the textbox readonly <input type="text" size="23" id="dateMonthly" readonly="readonly" style="background:white;" /> or via jquery $('#dateMonthly').attr('readonly', true);
[ "mathoverflow", "0000036452.txt" ]
Q: Explicit description of all morphisms between symmetric groups. There is a well-known morphism $S_4\to S_3$, obtained by having $S_4$ act on the three partitions of $4$ objects into $2+2$. Similarly, given any $n$, one can devise a morphism $S_n\to S_k$ for some $k$ by having $S_n$ act on the partitions of $n$ objects into $n_1+n_2+\ldots+n_\ell$. One can further endow some or all of the element of the partition with an order, for example with $\ell=1$ one has $S_n$ acting on the set of ordered sequences of size $n$, and gets the left action of $S_n$ on itself, which is a morphism $S_n\to S_{n!}$ (the largest one that is irreducible). Is that, are something close to that, the complete list of all morphisms $S_n\to S_k$ (up to conjugacy, of course)? I assume the answer is well-known. Edit: the question was really naive, but I would like to know if some general information are nevertheless available on the Burnside ring of $S_n$ (which encodes the permutation representations of a finite group, but this is almost all I know). A: Bret Benesh and Ben Newton determined all pairs $(m,n)$ such that $S_m$ contains a maximal subgroup isomorphic to $S_n$. They are either $(n+1,n)$ with the obvious inclusion (or mapping $S_5$ into the image of a point stabilizer under the outer automorphism of $S_6$); $(\binom{n}{k},n)$, coming from the action of $S_n$ on the subsets of $k$ elements of $\{1,2,\ldots,n\}$; and $((kr)!/(r!)^k k!, kr)$ with $1\lt k,r$, with $S_{kr}$ acting on the the right cosets of a maximal subgroups of the wreath product $S_k\wr S_r$. This appears in A classification of certain maximal subgroups of symmetric groups, J. Algebra 304 (no. 2) pp. 1108-1113, MR2265507. Bret later also determined all pairs $(m,n)$ such that $S_m$ has a maximal subgroup isomorphic to $A_n$; such that $A_m$ has a maximal subgroup isomorphic to $S_n$; and such that $A_m$ has a maximal subgroup isomorphic to $A_n$. This appears in the book Computational Group Theory and the Theory of Groups, Contemporary Mathematics 470 (L-C Kappe, R. F. Morse, and me as editors), AMS 2008; the paper is A classification of certain maximal subgroups of alternating groups, pp. 21-26, MR2478411. As pointed out by Jack, this does exhaust all possible embeddings of $S_n$ into $S_k$ (presumably you are okay with the maps that are not embeddings...)
[ "stackoverflow", "0008385796.txt" ]
Q: java/jsonsimple - use key to get value from a jsonarray I have the following example json output form java/jsonsimple. The JSONArray is: [{"dd1":{"actionType":"Dept","collegeID":""}},{"dd2":{"actionType":"Dept","collegeID":""}}] I'm trying to figure out how to get the value for the "dd1" key by using the "dd1" instead of the ndx. basically, I want to be able to test for a given "key" to see if it's in the array, with a value. The docs for JSONArray, allow for foo.get(1), but not foo.get("dd1") thanks ps. I tried to use the insert the above into a JSONObject, and then do a foo.get("dd1") but I didn't get the value. The issue appears to come down to figuring out how to get dict that's in the [] array. doing something like foo.get(1).get("dd1") doesn't work... thanks A: You have an array wrapping your dictionary in your JSON input, so you'd have to get the dictionary first, something like: foo.get(1).get("dd1"); But you can change your JSON to be a simple dictionary, like this: { "dd1": {"actionType":"Dept","collegeID":""}, "dd2": {"actionType":"Dept","collegeID":""} } And then you'll be able to do: foo.get("dd1");
[ "stackoverflow", "0015610433.txt" ]
Q: Detecting mobile devices I have a Javascript code where I detect if my site is viewed from a mobile device. Below is my code: (function() { if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) || navigator.userAgent.match(/Opera Mini/i) || navigator.userAgent.match(/IEMobile/i) ) { isMobile = true; } })(); Does this code cover all the possible cases or is there are chance that some devices can bypass this check? A: This is the best I found so far: http://detectmobilebrowsers.com/ and is is free. For example jQuery: 1) download the file from the site above 2) full listing down under /** * jQuery.browser.mobile (http://detectmobilebrowser.com/) * * jQuery.browser.mobile will be true if the browser is a mobile device * **/ (function(a){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera); 3) use the following: /** * jQuery.browser.mobile (http://detectmobilebrowser.com/) * * jQuery.browser.mobile will be true if the browser is a mobile device * **/ basically if you write an alert: alert(jQuery.browser.mobile); after the above code the popup will show true or false according to your mobile device.
[ "stackoverflow", "0052357694.txt" ]
Q: Paste Together Consecutive Non-Digit Elements Question After identifying elements in a character vector that satisfies a non-digit pattern, how can I paste together those elements that consecutively satisfy the regex pattern? Overview sample_text mostly contains two patterns: odd elements: contain 6-digits followed by text; even elements: contain 4-digits followed by text. However, there are a few instances of non-digit text that belong to the odd element that precedes it. Previous Solution Previously, I was unaware of consecutive non-digit elements in the character vector. This allowed me to manually paste each non-digit element to the element which was directly two elements behind the non-digit element. # load necessary package library(tidyverse) -------- # load necessary data ------ sample_text <- c("811411 Home and Garden Equipment Repair and" , "7699 Repair Services, Nec" , "Maintenance" # non-digit pattern , "811412 Appliance Repair and Maintenance" , "7623 Refrigeration Service and Repair" , "811412 Appliance Repair and Maintenance" , "7629 Electrical Repair Shops") # previous solution ------- sample_text %>% # for those elements which satisfy the non-digit pattern # identify the index of those elements which are exactly two behind replace(list = str_detect(., "^\\D*$") %>% which() - 2 # of those elements which are exactly two behind the non-digit pattern # paste the non-digit pattern to the end of them. , values = paste(.[str_detect(., "^\\D*$") %>% which() - 2] , str_subset(., "^\\D*$"))) %>% # only keep elements with digits str_subset("\\d") # [1] "811411 Home and Garden Equipment Repair and Maintenance" # successfully copied the non-digit element and pasted it two elements behind # [2] "7699 Repair Services, Nec" # [3] "811412 Appliance Repair and Maintenance" # [4] "7623 Refrigeration Service and Repair" # [5] "811412 Appliance Repair and Maintenance" # [6] "7629 Electrical Repair Shops" # end of script # Current Problem Now that I realize sample_text contains consecutive non-digit elements, I am unsure how to update my previous solution. Any help would be much appreciated! # sample data ----- sample_text <- c("811310 Commercial and Industrial Machinery and" , "7692 Welding Repair" , "Equipment (except Automotive and" # non-digit pattern (1/2) , "Electronic) Repair and Maintenance" # non-digit pattern (2/2) , "811310 Commercial and Industrial Machinery and" , "7694 Armature Rewinding Shops" , "Equipment (except Automotive and" # non-digit pattern (1/2) , "Electronic) Repair and Maintenance" # non-digit pattern (2/2) , "811310 Commercial and Industrial Machinery and" , "7699 Repair Services, Nec" , "Equipment (except Automotive and" # non-digit pattern (1/2) , "Electronic) Repair and Maintenance" # non-digit pattern (2/2) , "811411 Home and Garden Equipment Repair and" , "7699 Repair Services, Nec" , "Maintenance" # non-digit pattern (1/1) , "811412 Appliance Repair and Maintenance" , "7623 Refrigeration Service and Repair" , "811412 Appliance Repair and Maintenance" , "7629 Electrical Repair Shops" , "811412 Appliance Repair and Maintenance" , "7699 Repair Services, Nec") # desired output ------ [1] "811310 Commercial and Industrial Machinery and Equipment (except Automotive and Electronic) Repair and Maintenance" [2] "7692 Welding Repair" [3] "811310 Commercial and Industrial Machinery and Equipment (except Automotive and Electronic) Repair and Maintenance" [4] "7694 Armature Rewinding Shops" [5] "811310 Commercial and Industrial Machinery and Equipment (except Automotive and Electronic) Repair and Maintenance" [6] "7699 Repair Services, Nec" [7] "811411 Home and Garden Equipment Repair and Maintenance" [8] "7699 Repair Services, Nec" [9] "811412 Appliance Repair and Maintenance" [10] "7623 Refrigeration Service and Repair" [11] "811412 Appliance Repair and Maintenance" [12] "7629 Electrical Repair Shops" [13] "811412 Appliance Repair and Maintenance" [14] "7699 Repair Services, Nec" A: Guessing from your expected output, you iterate over the vector and if a line does not contain any digits it should be added to the element before, i.e. current index - 1: x <- c() for(i in sample_text){ if(grepl("^\\D*$",i, perl=TRUE)) { x[length(x)-1] <- paste(x[length(x)-1], i) } else { x <- c(x, i) #append } } Output: [1] "811310 Commercial and Industrial Machinery and Equipment (except Automotive and Electronic) Repair and Maintenance" [2] "7692 Welding Repair" [3] "811310 Commercial and Industrial Machinery and Equipment (except Automotive and Electronic) Repair and Maintenance" [4] "7694 Armature Rewinding Shops" [5] "811310 Commercial and Industrial Machinery and Equipment (except Automotive and Electronic) Repair and Maintenance" [6] "7699 Repair Services, Nec" [7] "811411 Home and Garden Equipment Repair and Maintenance" [8] "7699 Repair Services, Nec" [9] "811412 Appliance Repair and Maintenance" [10] "7623 Refrigeration Service and Repair" [11] "811412 Appliance Repair and Maintenance" [12] "7629 Electrical Repair Shops" [13] "811412 Appliance Repair and Maintenance" [14] "7699 Repair Services, Nec" Online sample
[ "unix.stackexchange", "0000591228.txt" ]
Q: How to transform a CLI linux into a GUI one? Or at least how to run a gui app like firefox in CLI linux? Installing x windowing system? I just want somebody to walk me through the steps of switching a command line interface linux box into a gui based one. I know this has to do with the X Window System but I don't exactly know how to go about installing it fully. Now, if firefox is installed for example and I try to run it, it will give me: "error: no display environment variable specified" Of course I need to specify a display, right? I used this: export DISPLAY=:0 and when I typed firefox nothing happens. When I type firefox & and then enter the command jobs I can see that firefox is running. But nothing is displayed. No window pops up. I searched about how to solve this error but I didn't really get it. I just want to apply changes to my linux box so that when I open a gui based software it just opens with a window. Actually that's one thing that is doable. I have done it long ago but I forgot how as I'm not a regular linux user. The other thing that I want to know: Is it also doable to change a cli linux box into an overall gui based linux permanently like those which are ready made such as Ubuntu and linux mint? Or does that require an actual coder? I'm actually using a VM in virtualbox and experimenting with it. I can reverse any harm done to it. It is actually ubuntu 14.04 VM. It is the linux version of the metasoloitable3 VM by rapid7 used for pentesting: https://github.com/rapid7/metasploitable3 Thanks in advance A: For a minimal Gui use xorg apt install xorg If you would like to just use a GUI as in a desktop environment just do: apt install ubuntu-desktop after a restart you should be able to see the Gui A: You say you are using Ubuntu. To add the desktop. You need to install it. However you say you are using Ubuntu 14.04 Ubuntu version numbers are YY.MM (year and month of release) see support has been dropped (it still has long-term security support until 2020-04). To install do apt install kde-plasma-desktop (or other desktop) -- it will pull in all dependencies including X11. However it may be better to use a different Virtual machine for desktop use. You could run them both, and connect to the not graphical one from the graphical one. You can still run graphical programs on the non-graphical one but display them on the graphical one using ssh -X, and installing just the program (e.g. firefox), but no desktop.
[ "stackoverflow", "0016841489.txt" ]
Q: Count of related records but limit results I have tables of CUSTOMERS and ORDERS, related by customer_id. I just want to get the count of number of orders that have been placed by each customer. I was successful with this example sqlfiddle . However, the recordset is large and I just want to get the total number of records for each customer limited to those that have had that number change recently. One possible solution, list all customers that have placed an order in the last 30 days, and list their total number of orders ever placed. I tried one approach with this other SQL fiddle. I am trying to SELECT TOP 3 customers and their total number of orders, sorted by their order date. This doesn't work, and only shows the number of orders placed by each customer within that truncated time period. A: I think you're a bit confused with your SELECT TOP (3) and ORDER BY. Go with your initial query with an additional WHERE clause; SELECT customer_id, COUNT(order_id) AS num_orders FROM Customers LEFT JOIN Orders ON (customer_id = cust_id) WHERE order_date > DATE() - 30 // or desired equivalent GROUP BY customer_id; Edit As per your latest comment... SELECT customer_id, COUNT(order_id) AS num_orders FROM Customers LEFT JOIN Orders ON (customer_id = cust_id) WHERE customer_id IN(SELECT TOP (3) [cust_id] FROM Orders ORDER BY [order_date] DESC) GROUP BY customer_id SQL Fiddle This will select the ids of the most recent three orders and return the total number of orders for each associated customer.
[ "stackoverflow", "0003504672.txt" ]
Q: XSLT blank xmlns="" after transform I'm using an XSLT to transform from one XML standard to another. The particular resulting XML standard contains a root element which is part of a namespace and a child node which is part of another namepsace. The transform successfully reflects these namespaces but the child's child now contains a blank xmlns attribute. How can I prevent this xmlns=""? XSLT Snippet: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" > <xsl:output method="xml" indent="yes"/> <xsl:template match="@* | node()"> <xsl:apply-templates select="REQUEST_GROUP" /> </xsl:template> <xsl:template match="REQUEST_GROUP"> <ONCORE_ERECORD xmlns="http://test.com"> <xsl:apply-templates select="REQUEST/PRIA_REQUEST/PACKAGE"/> <PAYMENT PaymentType="ACH" /> <TRANSACTION_INFO _AgentKey="" _AgentPassword="" /> </ONCORE_ERECORD> </xsl:template> <xsl:template match="PACKAGE"> <DOCUMENT_RECORDATION xmlns="http://test2.org"> <xsl:apply-templates select="PRIA_DOCUMENT"/> </DOCUMENT_RECORDATION> </xsl:template> <xsl:template match="PRIA_DOCUMENT"> <PRIA_DOCUMENT _PRIAVersion="1.2"> <xsl:attribute name="_Type"> <xsl:value-of select="@RecordableDocumentType"/> </xsl:attribute> <xsl:attribute name="_Code"/> <xsl:apply-templates select="GRANTOR" /> <xsl:apply-templates select="GRANTEE" /> <xsl:choose> <xsl:when test="count(PROPERTY) = 0"> <PROPERTY> <xsl:attribute name="_StreetAddress"> <xsl:value-of select="@StreetAddress"/> </xsl:attribute> <xsl:attribute name="_StreetAddress2"> <xsl:value-of select="@StreetAddress2"/> </xsl:attribute> <xsl:attribute name="_City"> <xsl:value-of select="@City"/> </xsl:attribute> <xsl:attribute name="_State"> <xsl:value-of select="@State"/> </xsl:attribute> <xsl:attribute name="_PostalCode"> <xsl:value-of select="@PostalCode"/> </xsl:attribute> <xsl:attribute name="_County"> <xsl:value-of select="@County"/> </xsl:attribute> <xsl:apply-templates select="LEGAL_DESCRIPTION"/> </PROPERTY> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="PROPERTY" /> </xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="count(PARTIES) = 0"> <PARTIES> <_RETURN_TO_PARTY _UnparsedName="" _StreetAddress="" _StreetAddress2="" _City="" _State="" _PostalCode="" /> </PARTIES> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="PARTIES" /> </xsl:otherwise> </xsl:choose> <xsl:apply-templates select="EXECUTION" /> <xsl:apply-templates select="CONSIDERATION" /> <xsl:apply-templates select="RECORDABLE_DOCUMENT/_ASSOCIATED_DOCUMENT" /> <xsl:apply-templates select="EMBEDDED_FILE" /> </PRIA_DOCUMENT> Source XML: <REQUEST_GROUP PRIAVersionIdentifier="2.4"> <REQUEST> <PRIA_REQUEST _Type="RecordDocuments"> <PACKAGE> <PRIA_DOCUMENT PRIAVersionIdentifier="2.4" RecordableDocumentSequenceIdentifier="1" RecordableDocumentType="Mortgage"> Resulting XML: <?xml version="1.0" encoding="utf-8"?> <ONCORE_ERECORD xmlns="http://test.com"> <DOCUMENT_RECORDATION xmlns="http://test2.org"> <PRIA_DOCUMENT _PRIAVersion="1.2" _Type="Mortgage" _Code="" xmlns=""> A: This is happening because PRIA_DOCUMENT is in the default namespace, while its parent DOCUMENT_RECORDATION is in a non-default namespace. You must put the PRIA_DOCUMENT in the same namespace as its parent, otherwise the serializer is required to generate xmlns="". . . <xsl:template match="PRIA_DOCUMENT"> <PRIA_DOCUMENT _PRIAVersion="1.2" xmlns="http://pria.org"> . . . See Michael Kay's "XSLT 2.0 and XPATH 2.0, 4th edition", page 475 where he discusses this exact situation. A: I found a solution that worked, though it may not have been the most efficient way to achieve the desired results. I simply changed all literal element declarations to: </xsl:element> and declared the namespace. The resulting xslt is as follows: <xsl:template match="REQUEST_GROUP"> <xsl:element name="ONCORE_ERECORD" namespace="http://test.com"> <xsl:apply-templates select="REQUEST/PRIA_REQUEST/PACKAGE"/> <xsl:element name="PAYMENT" namespace="http://test.com"> <xsl:attribute name="PaymentType"> <xsl:value-of select="'ACH'"/> </xsl:attribute> </xsl:element> <xsl:element name="TRANSACTION_INFO" namespace="http://test.com"> <xsl:attribute name="_AgentKey"> <xsl:value-of select="''"/> </xsl:attribute> <xsl:attribute name="_AgentPassword"> <xsl:value-of select="''"/> </xsl:attribute> </xsl:element> </xsl:element> </xsl:template> <xsl:template match="PACKAGE"> <xsl:element name="DOCUMENT_RECORDATION" namespace="http://test2.org"> <xsl:apply-templates select="PRIA_DOCUMENT"/> </xsl:element> </xsl:template> <xsl:template match="PRIA_DOCUMENT"> <xsl:element name="PRIA_DOCUMENT" namespace="http://test2.org"> <xsl:attribute name="_PRIAVersion"> <xsl:value-of select="'1.2'"/> </xsl:attribute> <xsl:attribute name="_Type"> <xsl:value-of select="@RecordableDocumentType"/> </xsl:attribute> <xsl:attribute name="_Code"/> <xsl:apply-templates select="GRANTOR" /> <xsl:apply-templates select="GRANTEE" /> <xsl:choose> <xsl:when test="count(PROPERTY) = 0"> <xsl:element name="PROPERTY" namespace="http://test2.org"> <xsl:attribute name="_StreetAddress"> <xsl:value-of select="@StreetAddress"/> </xsl:attribute> <xsl:attribute name="_StreetAddress2"> <xsl:value-of select="@StreetAddress2"/> </xsl:attribute> <xsl:attribute name="_City"> <xsl:value-of select="@City"/> </xsl:attribute> <xsl:attribute name="_State"> <xsl:value-of select="@State"/> </xsl:attribute> <xsl:attribute name="_PostalCode"> <xsl:value-of select="@PostalCode"/> </xsl:attribute> <xsl:attribute name="_County"> <xsl:value-of select="@County"/> </xsl:attribute> <xsl:apply-templates select="LEGAL_DESCRIPTION"/> </xsl:element> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="PROPERTY" /> </xsl:otherwise> </xsl:choose> <xsl:choose> <xsl:when test="count(PARTIES) = 0"> <xsl:element name="PARTIES" namespace="http://test2.org"> <xsl:element name="_RETURN_TO_PARTY" namespace="http://test2.org"> <xsl:attribute name="_UnparseName"> <xsl:value-of select="''"/> </xsl:attribute> <xsl:attribute name="_StreetAddress"> <xsl:value-of select="''"/> </xsl:attribute> <xsl:attribute name="_StreetAddress2"> <xsl:value-of select="''"/> </xsl:attribute> <xsl:attribute name="_City"> <xsl:value-of select="''"/> </xsl:attribute> <xsl:attribute name="_State"> <xsl:value-of select="''"/> </xsl:attribute> <xsl:attribute name="_PostalCode"> <xsl:value-of select="''"/> </xsl:attribute> </xsl:element> </xsl:element> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="PARTIES" /> </xsl:otherwise> </xsl:choose> <xsl:apply-templates select="EXECUTION" /> <xsl:apply-templates select="CONSIDERATION" /> <xsl:apply-templates select="RECORDABLE_DOCUMENT/_ASSOCIATED_DOCUMENT" /> <xsl:apply-templates select="EMBEDDED_FILE" /> </xsl:element> </xsl:template> A: Put the calling template and the applied template in the same namespace.
[ "stackoverflow", "0014616310.txt" ]
Q: cleaning out optional arguments and passing it out shell script I am trying to execute a cpp binary from shell script.. The cpp takes arguments and some of them are optional. So basically what I am trying to do is generating the appropiate string and then executing that string something like: generate_string() { string="$path/to/binary" param1=$1 param2=$2 generated_string="$string $param1 --param2=$param2" echo $generated_string } # execution function execute() { read -p 'param1: ' param2 read -p 'param2: ' param2 echo 'optional arguments' *read -p "param3: " param3 read -p "param4: " param4* string=$(generate_string $param1 $param2 ???????) eval $string } Now in this function.. either or both of param3 and param4 can be blank What I want is if it is blank then offcourse I dont generate it in a string. But I feel its too messy to have if statements.. Is there a way to solve this gracefully A: This should work sir #!/bin/sh usage () { echo usage: $0 PARAM1 PARAM2 [PARAM3] [PARAM4] exit } [ $2 ] || usage eval "path/to/binary" "$@"
[ "stackoverflow", "0004291849.txt" ]
Q: JSF - Can @PostConstruct block setter method by using an ajax call? I think the question is clear by the title. This is my actual bean : @ManagedBean(name="selector") @RequestScoped public class Selector { private String profilePage; @PostConstruct public void init() { System.out.println("I'm PostConstruct"); if(profilePage==null || profilePage.trim().isEmpty()) { this.profilePage="main"; } } public String getProfilePage() { return profilePage; } public void setProfilePage(String profilePage) { this.profilePage=profilePage; System.out.println("I'm setProfilePage"); } } And i change his value (profilePage) by using ajax call : <h:commandButton value="Some Action"> <f:setPropertyActionListener target="#{selector.profilePage}" value="some" /> <f:ajax event="action" render=":profileContent"/> </h:commandButton> I notice that my output on server is not ever a sequence of I'm PostConstruct followed by I'm setProfilePage. Sometimes I'm setProfilePage is totally absent. I read that Methods marked with the @PostConstruct annotation will be invoked after the bean has been created, any resources have been injected, and any managed properties set, but before the bean is actually pushed into scope. I would like to know if @PostConstruct can make some conflicts with setter method. Cheers A: Sometimes I'm setProfilePage is totally absent. That can happen when the UICommand component is not rendered in the component tree during apply request values phase and/or update model values phase. I.e. the rendered attribute of it or one of its parents has evaluated false at that point. The presence of @PostConstruct should not have any influence.
[ "math.stackexchange", "0000011026.txt" ]
Q: Inverse of a monoid homomorphism It is a well-known fact that $f\colon a \mapsto \left(\begin{array}{cc} 1 & 1\\ 0 & 1\\ \end{array}\right), ~ b \mapsto \left(\begin{array}{cc} 1 & 0\\ 1 & 1\\ \end{array}\right)$ is a monomorphism from the free monoid generated by $a$ and $b$ to the matrix monoid $\mathbb{Z}^{2\times 2}$. Is there an efficient algorithm which computes the length of $f^{-1}(X)$ from $X \in \mathbb{Z}^{2\times 2}$ (that is, the number of symbols in corresponding word $x$, if $f^{-1}(X) = \{x\}$)? Is there an efficient algorithm which computes $f^{-1}(X)$ from $X \in \mathbb{Z}^{2\times 2}$? Is there a standard reference for this problem? A: Yes; see the Wikipedia article on Smith normal form. In two dimensions you are essentially using the Euclidean algorithm. Edit: The basic observation here is that if $M = \left[ \begin{array}{cc} x & y \\\ z & w \end{array} \right]$ is an integer matrix, then $$M f(a^{-1}) = \left[ \begin{array}{cc} x & y - z \\\ z & w - z \end{array} \right]$$ and similarly $$M f(b^{-1}) = \left[ \begin{array}{cc} x - y & y \\\ z - w & w \end{array} \right].$$ If in addition $\det M = 1$ and $x, y, z, w$ are non-negative integers, then exactly one of these operations will give a matrix with the same properties (this is equivalent to $f$ being a monomorphism). So, as I said, essentially one is performing the Euclidean algorithm on the columns (or, if you multiply from the left instead, on the rows). As an example, if $M = \left[ \begin{array}{cc} 8 & 5 \\\ 3 & 2 \end{array} \right]$, then $$M f(b^{-1}) = \left[ \begin{array}{cc} 3 & 5 \\\ 1 & 2 \end{array} \right]$$ $$M f(b^{-1} a^{-1}) = \left[ \begin{array}{cc} 3 & 2 \\\ 1 & 1 \end{array} \right]$$ $$M f(b^{-1} a^{-1} b^{-1}) = \left[ \begin{array}{cc} 1 & 2 \\\ 0 & 1 \end{array} \right] = f(aa)$$ hence $M = f(aabab)$ as desired.
[ "stackoverflow", "0008472204.txt" ]
Q: Capture all mouse events in user control I'm trying to capture all mouse events in a user control (even the ones that occur in child controls). For that I use the "override WndProc"-approach: protected override void WndProc(ref Message m) { System.Diagnostics.Debug.WriteLine(m.Msg.ToString()); base.WndProc(ref m); } I'm especially interested in mouse events, but that does not seem to work. I do get mouse button up/down events, but I don't get mouse move and mouse wheel events. Any ideas? A: Best you could do is implement IMessageFilter in your control. public class CustomMessageFilter:UserControl,IMessageFilter { public bool PreFilterMessage(ref Message m) { //Process your message here throw new NotImplementedException(); } } you can write your message filtering logic in PreFilterMessage Method. Then just install it to the list of Message Filter in Main method. Application.AddMessageFilter(new CustomMessageFilter()); This is a Application level hook, that means you can control all the Win32 message within application.
[ "stackoverflow", "0016482852.txt" ]
Q: Django Google Suspicious Operation I'm new to Django, and keep getting the same error emailed to me. It's regarding the allowed hosts (using Django 1.5). Why does it see Google as Suspicious? Should I allow Google, will it stop my site from being indexed? Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 92, in get_response response = middleware_method(request) File "/usr/local/lib/python2.7/dist-packages/newrelic-1.11.0.55/newrelic/api/object_wrapper.py", line 216, in __call__ self._nr_instance, args, kwargs) File "/usr/local/lib/python2.7/dist-packages/newrelic-1.11.0.55/newrelic/hooks/framework_django.py", line 204, in wrapper return wrapped(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/middleware/common.py", line 57, in process_request host = request.get_host() File "/usr/local/lib/python2.7/dist-packages/django/http/request.py", line 72, in get_host "Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): %s" % host) SuspiciousOperation: Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): www.google.com <WSGIRequest path:/, GET:<QueryDict: {}>, POST:<QueryDict: {}>, COOKIES:{}, META:{'DOCUMENT_ROOT': '/srv/project/sms', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HTTP_ACCEPT': 'text/html', 'HTTP_HOST': 'www.google.com', 'HTTP_PROXY_CONNECTION': 'close', 'HTTP_USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)', 'PATH_INFO': u'/', 'PATH_TRANSLATED': '/srv/project/sms/apache/django.wsgi/', 'QUERY_STRING': '', 'REMOTE_ADDR': '183.91.14.60', 'REMOTE_PORT': '55739', 'REQUEST_METHOD': 'GET', 'REQUEST_URI': 'http://www.google.com/', 'SCRIPT_FILENAME': '/srv/project/sms/apache/django.wsgi', 'SCRIPT_NAME': u'', 'SERVER_ADDR': '10.229.37.116', 'SERVER_ADMIN': '[no address given]', 'SERVER_NAME': 'www.google.com', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.0', 'SERVER_SIGNATURE': '<address>Apache/2.2.22 (Ubuntu) Server at www.google.com Port 80</address>\n', 'SERVER_SOFTWARE': 'Apache/2.2.22 (Ubuntu)', 'mod_wsgi.application_group': 'www.domain.com|', 'mod_wsgi.callable_object': 'application', 'mod_wsgi.handler_script': '', 'mod_wsgi.input_chunked': '0', 'mod_wsgi.listener_host': '', 'mod_wsgi.listener_port': '80', 'mod_wsgi.process_group': 'domain.com', 'mod_wsgi.request_handler': 'wsgi-script', 'mod_wsgi.script_reloading': '1', 'mod_wsgi.version': (3, 3), 'wsgi.errors': <mod_wsgi.Log object at 0x7f348e39a6f0>, 'wsgi.file_wrapper': <built-in method file_wrapper of mod_wsgi.Adapter object at 0x7f348e3f7d50>, 'wsgi.input': <newrelic.api.web_transaction.WSGIInputWrapper object at 0x7f348de819d0>, 'wsgi.multiprocess': True, 'wsgi.multithread': True, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 1)}> A: Someone from 183.91.14.60 (REMOTE_ADDR) is connecting to your server and asking for Google's home page (REQUEST_URI); as you are not hosting Google this is indeed suspicious. This is not related to the Google index bot. I have also seen this request on my server (but not this error message) from this IP address. My guess is someone is scanning servers looking for open proxies. I would not add www.google.com to any allowed host list. If you are receiving a lot of these from the same REMOTE_ADDR I would consider adding that IP address to /etc/hosts.deny or to a block list on your firewall. How to do this will depend on your set up and is, I suspect, beyond the scope of StackOverflow.
[ "math.stackexchange", "0000315886.txt" ]
Q: A question about Exponents I've been reading about Exponents, and I was wondering if there is a shorter way to do this same calculation, below: 24 = 2 * 2 * 2 * 2 = 16 I keep seeing what seems to me a pattern in this, and other examples. The pattern I keep seeing (maybe it's a coincidence?), is that they always seem to only multiply the base number by the base number, until it reaches the same value that you would reach if you just multiplied the exponent by itself, just once. What I mean is, can we not just do it this way instead? 24 = 4 * 4 = 16 I.e. Instead of multiplying the base by the base a billion times, we just multiply the exponent by itself, once. And how do we calculate the power of using just the Windows calculator? A: What you saw is a bit of a coincidence since $2^2=4$. What was used here is this: $$2^{4}=2^{2\cdot2}=(2^{2})^{2}=4^{2}=16$$ A: The pattern is a only coincidence that occurs when the base is 2. Take an example when the base is 3: $3^4 = 3*3*3*3 = 81$ $3^4$ is not $4*4 = 16$
[ "stackoverflow", "0025041444.txt" ]
Q: Android Xml Pull Parser error - SitesDownloadTask.onPostExecute I have different three Adapters and three XML Parsers in my application for three Fragments sliding on ViewPager. My application works fine until I start sliding a little faster between first and second, or second and third fragment. Log Cat messagess: When sliding between first and second: FATAL EXCEPTION: main Process: com.intera.eronetmarket, PID: 3326 java.lang.NullPointerException at android.widget.ArrayAdapter.init(ArrayAdapter.java:310) at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:153) at adapters.KatAdapter.<init>(KatAdapter.java:32) at com.intera.eronetmarket.Kategorije$SitesDownloadTask.onPostExecute(Kategorije.java:98) at com.intera.eronetmarket.Kategorije$SitesDownloadTask.onPostExecute(Kategorije.java:1) at android.os.AsyncTask.finish(AsyncTask.java:632) at android.os.AsyncTask.access$600(AsyncTask.java:177) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) When Sliding between second and third: FATAL EXCEPTION: main Process: com.intera.eronetmarket, PID: 3359 java.lang.NullPointerException at com.intera.eronetmarket.Preporuceno$AppDownloadTask.onPostExecute(Preporuceno.java:85) at com.intera.eronetmarket.Preporuceno$AppDownloadTask.onPostExecute(Preporuceno.java:1) at android.os.AsyncTask.finish(AsyncTask.java:632) at android.os.AsyncTask.access$600(AsyncTask.java:177) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) My first fragment where AppDownlodTask class is. It is same in all 3 fragments (only adapters are different for each fragment): public class Preporuceno extends Fragment { private AppAdapter mAdapter; private ListView siteList; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.i("mobAppModel", "OnCreate()"); View rootView = inflater.inflate(R.layout.activity_preporuceno, container, false); siteList = (ListView) rootView.findViewById(R.id.listView1); siteList.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View v, int pos,long id) { String url = mAdapter.getItem(pos).getstoreURL(); Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }); if(isNetworkAvailable()){ Log.i("mobAppModel", "starting download Task"); AppDownloadTask download = new AppDownloadTask(); download.execute(); }else{ mAdapter = new AppAdapter(getActivity().getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(getActivity())); siteList.setAdapter(mAdapter); } return rootView; } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } private class AppDownloadTask extends AsyncTask<Void, Void, Void>{ @Override protected Void doInBackground(Void... arg0) { //Download the file try { Downloader.DownloadFromUrl("https://dl.dropboxusercontent.com/s/te0c0s7y7zr79tm/kategorijeXML.xml", getActivity().openFileOutput("XMLsource.xml", Context.MODE_PRIVATE)); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result){ //setup our Adapter and set it to the ListView. mAdapter = new AppAdapter(getActivity().getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(getActivity())); siteList.setAdapter(mAdapter); Log.i("mobAppModel", "adapter size = "+ mAdapter.getCount()); } } } My Adapters: package adapters; import java.util.List; import models.KatModel; import android.annotation.SuppressLint; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.RelativeLayout; import android.widget.TextView; import com.intera.eronetmarket.R; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; /* * Custom Adapter class that is responsible for holding the list of sites after they * get parsed out of XML and building row views to display them on the screen. */ public class KatAdapter extends ArrayAdapter<KatModel> { ImageLoader imageLoader; DisplayImageOptions options; public KatAdapter(Context ctx, int textViewResourceId, List<KatModel> sites) { super(ctx, textViewResourceId, sites); //Setup the ImageLoader, we'll use this to display our images ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).build(); imageLoader = ImageLoader.getInstance(); if (!imageLoader.isInited()) { imageLoader.init(config); } //Setup options for ImageLoader so it will handle caching for us. options = new DisplayImageOptions.Builder() .cacheInMemory() .cacheOnDisc() .build();} /* * (non-Javadoc) * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup) * * This method is responsible for creating row views out of a StackSite object that can be put * into our ListView */ @SuppressLint("InflateParams") @Override public View getView(int pos, View convertView, ViewGroup parent){ RelativeLayout row = (RelativeLayout)convertView; Log.i("StackSites", "getView pos = " + pos); if(null == row){ //No recycled View, we have to inflate one. LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = (RelativeLayout)inflater.inflate(R.layout.row_site, null); } //Get our View References TextView nameTxt = (TextView)row.findViewById(R.id.nameTxt); //Initially we want the progress indicator visible, and the image invisible //Load the image and use our options so caching is handled. //Set the relavent text in our TextViews nameTxt.setText(getItem(pos).getcategoryName()); return row; } } -- package adapters; import java.util.List; import models.mobAppModel; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import com.intera.eronetmarket.R; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.assist.ImageLoadingListener; @SuppressLint("InflateParams") public class AppAdapter extends ArrayAdapter<mobAppModel>{ ImageLoader imageLoader; DisplayImageOptions options; public AppAdapter(Context ctx,int textViewResourceId, List<mobAppModel> appModel){ super(ctx,textViewResourceId,appModel); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).build(); imageLoader = ImageLoader.getInstance(); if (!imageLoader.isInited()) { imageLoader.init(config); } options= new DisplayImageOptions.Builder() .cacheInMemory() .cacheOnDisc() .build(); } public View getView(int pos, View convertView, ViewGroup parent){ RelativeLayout row = (RelativeLayout)convertView; Log.i("mobAppModels", "getView pos = " + pos); if(null == row){ //No recycled View, we have to inflate one. LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = (RelativeLayout)inflater.inflate(R.layout.row_app, null); } //Get our View References final ImageView iconImg = (ImageView)row.findViewById(R.id.iconUrl); final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress); //Initially we want the progress indicator visible, and the image invisible indicator.setVisibility(View.VISIBLE); iconImg.setVisibility(View.INVISIBLE); //Setup a listener we can use to swtich from the loading indicator to the Image once it's ready ImageLoadingListener listener = new ImageLoadingListener(){ @Override public void onLoadingStarted(String arg0, View arg1) { // TODO Auto-generated method stub } @Override public void onLoadingCancelled(String arg0, View arg1) { // TODO Auto-generated method stub } @Override public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) { indicator.setVisibility(View.INVISIBLE); iconImg.setVisibility(View.VISIBLE); } @Override public void onLoadingFailed(String arg0, View arg1, FailReason arg2) { // TODO Auto-generated method stub } }; //Load the image and use our options so caching is handled. imageLoader.displayImage(getItem(pos).getimageUrl(),iconImg,options,listener); //Set the relavent text in our TextViews return row; } } -- package adapters; import java.util.List; import models.mobAppModel; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.RatingBar; import com.intera.eronetmarket.R; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.assist.ImageLoadingListener; public class AppAdapterNajpop extends ArrayAdapter<mobAppModel>{ ImageLoader imageLoader; DisplayImageOptions options; public AppAdapterNajpop(Context ctx,int textViewResourceId, List<mobAppModel> appModel){ super(ctx,textViewResourceId,appModel); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).build(); imageLoader = ImageLoader.getInstance(); if (!imageLoader.isInited()) { imageLoader.init(config); } options= new DisplayImageOptions.Builder() .cacheInMemory() .cacheOnDisc() .build(); } @SuppressLint("InflateParams") public View getView(int pos, View convertView, ViewGroup parent){ RelativeLayout row = (RelativeLayout)convertView; Log.i("mobAppModels", "getView pos = " + pos); if(null == row){ //No recycled View, we have to inflate one. LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = (RelativeLayout)inflater.inflate(R.layout.row_app_najpopularnije, null); } //Get our View References final ImageView iconImg = (ImageView)row.findViewById(R.id.iconUrl); TextView appHeadline = (TextView)row.findViewById(R.id.textView1); TextView developer = (TextView)row.findViewById(R.id.textView2); RatingBar ratingpoints =(RatingBar)row.findViewById(R.id.ratingBar); final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress); //Initially we want the progress indicator visible, and the image invisible indicator.setVisibility(View.VISIBLE); iconImg.setVisibility(View.INVISIBLE); //Setup a listener we can use to swtich from the loading indicator to the Image once it's ready ImageLoadingListener listener = new ImageLoadingListener(){ @Override public void onLoadingStarted(String arg0, View arg1) { // TODO Auto-generated method stub } @Override public void onLoadingCancelled(String arg0, View arg1) { // TODO Auto-generated method stub } @Override public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) { indicator.setVisibility(View.INVISIBLE); iconImg.setVisibility(View.VISIBLE); } @Override public void onLoadingFailed(String arg0, View arg1, FailReason arg2) { // TODO Auto-generated method stub } }; //Load the image and use our options so caching is handled. imageLoader.displayImage(getItem(pos).geticonUrl(),iconImg,options,listener); //Set the relavent text in our TextViews appHeadline.setText(getItem(pos).getappHeadline()); developer.setText(getItem(pos).getdeveloper()); ratingpoints.setRating(Float.parseFloat(getItem(pos).getratingPoints())); return row; } } When I slide slower, everything works fine. What is wrong? :\ A: As your flip quickly from fragment A to B, A might be destroyed at any time and you have no control on that. Before the fragment destroying process finish, it will also be detached from the activity. Starting from this moment, any call go getActivity() may returns null. So your issue is that your fragment has not a reference to an activity, but the async task still is running in a background thread, leading to null pointer exceptions. I'd suggest you to do: Activity attached = getActivity(); if (attached != null) { mAdapter = new AppAdapter(attached.getApplicationContext(), -1, XMLsourcePullParser.getmobAppModel(getActivity())); siteList.setAdapter(mAdapter); } More about this issue in:http://developer.android.com/guide/components/fragments.html#Lifecycle . I'd like to highlight the Caution session: if you need a Context object within your Fragment, you can call getActivity(). However, be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null.
[ "academia.stackexchange", "0000007365.txt" ]
Q: What will happen to my IEEE conference paper if the status of the accepted paper is "AAR" I have been notified by the IEEE organizing committee that my paper has been accepted for their conference and requested to register. and the status of the paper is AAR. Please see the quotation below. [AAR]This paper need thorough revision to be accepted as a full paper for the conference. I have attached an image of their review process. What will happen to my paper after the submission of the camera-ready paper? Is there any possibility for my paper not to be published in the proceedings and IEEE Xplore? Or is it guaranteed to be published after the submission of camera-ready paper? A: I think the flowchart in your question is pretty clear as to what happens next. But I'll break down the relevant part of the flowchart into words. You have to make thorough revisions to your paper, and then resubmit. It will then be reviewed again. As a result of the review, it may be accepted, and it may be rejected. AAR: your paper's current status - accepted after revising. It's now up to you to make the thorough revisions, and to then submit the revised paper REV is the status your paper will have once you have submitted the revised paper. RVI will be its status when the revised paper has been sent out to review. Judging by the flowchart, it will get sent to the same editor and reviewers as before, because a revised paper does not pass through the WFR stage of waiting for review, where reviewers and editor are assigned. It may then be accepted (ACC), rejected (REJ), or conceivably, according to that flowchart, get returned to you once more as AAR for further revisions. The flowchart also suggests that whether it's accepted or rejected, you still prepare a camera-ready version. That would seem to be very unlikely: I find it very hard to believe there's any use for a camera-ready version of a rejected paper; only an accepted paper would need a camera-ready version. A: If the Journal/Conference editor/chair has accepted your paper, it is guaranteed to be published, given that you make the changes. That is the reason they emphasize the "review" part. Some papers have only minor revisions, so if the changes are not made, it won't affect that much the quality of the conference. But if the changes are major, it usually indicates that you have to step up the level of the paper following the suggestion of the reviewers. In conclusion, as long as you make the changes, your paper should be accepted in the conference, but if you neglect to do them, probably it wont.
[ "stackoverflow", "0000037830.txt" ]
Q: How do I implement a chromeless window with WPF? I want to show a chromeless modal window with a close button in the upper right corner. Is this possible? A: You'll pretty much have to roll your own Close button, but you can hide the window chrome completely using the WindowStyle attribute, like this: <Window WindowStyle="None"> That will still have a resize border. If you want to make the window non-resizable then add ResizeMode="NoResize" to the declaration. A: Check out this blog post on kirupa.
[ "stackoverflow", "0038847096.txt" ]
Q: Right XPath expression for XML when using XML::LibXML I have an issue in arriving at the right xpath to query data from xml. I use use XML::LibXML to do this The XML <?xml version="1.0" encoding="iso-8859-1"?> <data> <header> <date>2016-08-07</date> <name>Indices Composites</name> <version>1.1a</version> </header> <row> <CompositePrice>1.010227784212584</CompositePrice> <CompositeSpread>0.002568273865609903</CompositeSpread> <Date>2016-08-05</Date> <Depth>4</Depth> <Heat>0.0201994587386602</Heat> <IndexID>ITRAXX-SOVXWES8V1-5Y</IndexID> <Maturity>2017-12-20</Maturity> <ModelPrice>1.0103988929051526</ModelPrice> <ModelSpread>0.002445016658588964</ModelSpread> <Name>iTraxx SovX Westn Europe</Name> <OnTheRun>Y</OnTheRun> <REDCode>5C769MAO9</REDCode> <RequestKey>iTraxx SovX Westn Europe|5Y|Y</RequestKey> <Series>8</Series> <ShortName></ShortName> <Term>5Y</Term> <Version>1</Version> </row> <row> <CompositePrice>1.0208723593556004</CompositePrice> <CompositeSpread>0.006539233068666665</CompositeSpread> <Date>2016-08-05</Date> <Depth>3</Depth> <Heat>0.0307106033333336</Heat> <IndexID>ITRAXX-SOVXWES8V1-10Y</IndexID> <Maturity>2022-12-20</Maturity> <ModelPrice>1.0219657857189512</ModelPrice> <ModelSpread>0.006361337372712667</ModelSpread> <Name>iTraxx SovX Westn Europe</Name> <OnTheRun>Y</OnTheRun> <REDCode>5C769MAO9</REDCode> <RequestKey>iTraxx SovX Westn Europe|10Y|Y</RequestKey> <Series>8</Series> <ShortName></ShortName> <Term>10Y</Term> <Version>1</Version> </row> </data> I need to filter based on the values of certain tags. The code is like below. my $parser = XML::LibXML->new; my $doc = $parser->parse_file($inputFile); my @nodes = $doc->findnodes("/data/row/Name[text()='iTraxx SovX Westn Europe']/../Term[text()='5Y']/../OnTheRun[text()='Y']"); print "@nodes \n"; The output I get is <OnTheRun>Y</OnTheRun> whereas I would like to get the entire node which satisfies the condition. Is the XPath expression right here ? A: XPath expressions are very like Linux file paths. If you remove all the predicates from what you have written, you get /data/row/Name/../Term/../OnTheRun You can see here that, from the row element, you're descending into Name and going back up one level, then into Term and going back up one level, and finally into OnTheRun, where the expression stops This is why you see only the value of the OnTheRun element, and a simple fix would be to append another .. path step to get back up to the row element that you want to access This XPath expression works fine /data/row/Name[text()='iTraxx SovX Westn Europe']/../Term[text()='5Y']/../OnTheRun[text()='Y']/.. but it is very awkward to read I think the neatest way to do this is to apply multiple predicates to the main /data/row selector, like this /data/row[Name="iTraxx SovX Westn Europe"][Term="5Y"][OnTheRun="Y"] Here's a full program that uses it to process you sample data use strict; use warnings 'all'; use open IO => ":encoding(iso-8859-1)"; use XML::LibXML; my $doc = XML::LibXML->load_xml( location => 'indices_composites.xml' ); my @nodes = $doc->findnodes('/data/row[Name="iTraxx SovX Westn Europe"][Term="5Y"][OnTheRun="Y"]'); printf "%d node%s found:\n\n", scalar @nodes, @nodes == 1 ? '' : 's'; print $nodes[0], "\n"; output 1 node found: <row> <CompositePrice>1.010227784212584</CompositePrice> <CompositeSpread>0.002568273865609903</CompositeSpread> <Date>2016-08-05</Date> <Depth>4</Depth> <Heat>0.0201994587386602</Heat> <IndexID>ITRAXX-SOVXWES8V1-5Y</IndexID> <Maturity>2017-12-20</Maturity> <ModelPrice>1.0103988929051526</ModelPrice> <ModelSpread>0.002445016658588964</ModelSpread> <Name>iTraxx SovX Westn Europe</Name> <OnTheRun>Y</OnTheRun> <REDCode>5C769MAO9</REDCode> <RequestKey>iTraxx SovX Westn Europe|5Y|Y</RequestKey> <Series>8</Series> <ShortName/> <Term>5Y</Term> <Version>1</Version> </row>
[ "stackoverflow", "0055598969.txt" ]
Q: Is Virtual File System the correct concept for this application I am developing an application which, at a very high level, can be summarized as a hierarchical arrangement of black-boxes, with each such black-box having inputs and outputs. I would like to have a representation of these inputs and outputs (in the same hierarchical arrangement) on the filesystem so that at runtime, other processes can interact with my application through the filesystem to stimulate the desired inputs and read the corresponding outputs. My question is whether a Virtual File System is the correct implementation for this requirement? Some things that I have considered: Using a filesystem to interact between processes makes is very intuitive for humans to read/write these inputs/outputs, which is a critical need for my application Non filesystem approaches require additional custom tools to achieve the same simplicity for humans On Linux, /proc seems to already implement this concept Ideally, this should be a RAM resident filesystem, to avoid the latencies of disk access. My application is in Linux, written in C++ so hopefully I should be able to leverage some existing library for this A: FUSE (Filesystem in Userspace) would be an easy way to implement this and it has many different language options https://en.wikipedia.org/wiki/Filesystem_in_Userspace
[ "stackoverflow", "0023417471.txt" ]
Q: Can an Abstract Class in PHP Have a Default Method? I've most certainly got something very basic wrong here. Here is the code that is part of my Abstract Class: private $outarray = null; public function add_to_array($ahref, $docname, $description) { $row = array('ahref' => $ahref, 'docname' => $docname, 'description' => $description); if (!isset($this->outarray)) { $this->outarray = array(); } array_push($this->outArray, $row); } When I step through the code, though, the outArray remains null. It is never created and never populated. I'm still green with PHP, but this help doc seems to leave me believing that this is OK to do: http://www.php.net/manual/en/language.oop5.abstract.php ...particularly where they are declaring the Common method printOut() that performs some action. I've got 5 elements I am trying to populate outArray with, but each of the 5 times I circle into this function, I come out with outArray being NULL. A: Variables are case sensitive. You have in one place $this->outarray and in array_push you have $this->outArray
[ "stackoverflow", "0013203329.txt" ]
Q: Wordpress use functions.php to run function only on specific page template I have a following code to check if current used file is tmp_home_page.php, but when I do echo $template_file; it is showing functions.php add_action('template_redirect', 'are_we_home_yet', 10); function are_we_home_yet(){ global $template; $template_file = basename((__FILE__).$template); if ( is_home() && $template_file == 'tmp_home_page.php' ) { // do stuff } } Any idea how to make sure that my do stuff is only run on home page and when given template is in use? A: You're looking way too hard into this, there's a wordpress function for that. is_page_template() if( is_page_template( 'tmp_home_page.php' ) && is_home() ){ // Do Stuff } Also, is_front_page() is usually a better alternative to is_home() when trying to determine if a user is viewing the Front/First Page of a WordPress site. You can see more on that subject here.
[ "stackoverflow", "0033930011.txt" ]
Q: changing an edit text from another activiy after clicking a button Okay so I'm new at programming, and for a school project I have to make a coffee shop app in android studio. What I want to know, is how can I after clicking a button, edit a space for text to add text about the item they will buy but place it in another activity. The thing is I want to make a kind of add to cart thing, and after going to the cart tab, there is an edit text where you see how much the account will be. Can anyone help me with this?? A: You could use the Alert Dialog with Edit Text and pass the values using Shared Preference. AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this); LayoutInflater inflater=MainActivity.this.getLayoutInflater(); //this is what I did to added the layout to the alert dialog View layout=inflater.inflate(R.layout.editxml,null); alert.setView(layout); alert.setTitle("Enter Name"); final EditText usernameInput=(EditText)layout.findViewById(R.id.editText1); alert.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub //do your stuff here } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.show(); editxml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:id="@+id/editText1" /> </LinearLayout>