text
stringlengths
64
89.7k
meta
dict
Q: Set default button on html elements with jquery plugin I am looking at writing a jquery plugin that takes a number of input elemts such as input elements, textareas, select html elements etc and once the enter key is pressed in any of the above items, a input button is triggered. As such, the button is set as the default for the fields. Any tips on doing this? A: The first input type="submit"/"image"/button type="submit" in a form is the ‘default’ submit button. If the button you want to act as default should not appear first on the page, then move it around with eg. floats or positioning. Or, if that's not practical, simply have an extra dummy submit button as the first thing in the form, using position: absolute; left: -lots to make it effectively invisible. (You can use tabindex to stop it coming up in the normal tab order; don't use display: none or visibility: hidden as in some browsers that'll stop the button being considered for default.) Catch the default button/submit action from the form.onsubmit event and any other non-default buttons on their own onclick events. This is a bit of an ugly hack, and it's certainly a pity that HTML provides no way to change the default button naturally, but you are much better off leveraging native browser behaviour here than trying to replace it with scripting, which is trickier than you think. There are a lot of funny little browser behaviours that can trip you up. For example, if you decide to catch the Enter keypress, you may get unwanted Enter events from users using IMEs. Enter keypresses on an input type="button" or textarea generally shouldn't trigger submit. Enter keypress on a select probably should, except when the keyboard is being used to navigate the dropdown (and you can't reliably tell when that's happened). What if a non-field element inside the form gets focused and Enter is pressed? You won't catch it and in some browsers this will cause a form submit, without your code's intervention, ending up at the default button anyway. Does Shift-Enter or Ctrl-Enter mean submit in a text field? in a text area? Does Enter on a checkbox check it, submit the form, or both? ... Browsers have many subtly different behaviours here; you'll go mad trying to cover every last little possibility, and whatever you decide on will probably go against the user's expected behaviour. Let the browser's normal default-form-submit code handle it instead.
{ "pile_set_name": "StackExchange" }
Q: Getting input value that has its own iterated button upon click I've successfully added an iterator to my php foreach loop so that I can create a unique button for each row in my table. <?php $i = 1;?> @foreach($getPromoCodes as $codes) <input type="hidden" name="promo_code_id" id="promo_code_id[{{$i}}]" class="promo_code_id" value="{{ $codes->promo_codet_id }}"> <?php $i++;?> @endforeach However, I can't figure out, once the button is pressed, how to get the value of the input from the clicked button. This being due to the uniqueness of each button with the iterator. var promo_codet_id = document.getElementsByClassName("promo_code_id"); This returns undefined when I console log it. How do I need to change my JS for this? A: You can do this way: <div class="elements"> <?php $i = 1;?> <?php foreach($getPromoCodes as $codes): ?> <input type="hidden" name="promo_code_id" id="promo_code_id[{{$i}}]" class="promo_code_id" value="{{ $codes->promo_codet_id }}"> <a href="#" class="btn" data-id="<?= $i ?>">Link </a> <?php $i++;?> <?php endforeach; ?> </div> jquery: $('.elements').on('click', '.btn', function(e){ e.preventDefault(); console.log($(this).data('id')); });
{ "pile_set_name": "StackExchange" }
Q: When using Protractor 5.4.2, webdriver-manager downloads 2.46 which is not compatible with Chrome 74 Protractor 5.4.2 uses webdriver-manager 12 which downloads Chromedriver 2.46. Chromedriver 2.46 supports Chrome 71-73 (see http://chromedriver.chromium.org/downloads). We need to download Chromedriver 74.0.3729.6. I also see that there is a webdriver-manager@13 that supports this. Should I use it with Protractor 5.4.2? A: [email protected] is fixed webdriver-manager released 12.1.4 which will download a max ChromeDriver version of 74. How to get it? do a fresh install of your node modules directory (remove node_modules folder and do a npm install) do a forced install npm install -f If you want to download a version specific in 74.x.x.x, this has been fixed in 12.1.4. I introduced a bug when I tried to quickly fix the issue in 12.1.3 causing this to not work. Background on webdriver-manager downloading ChromeDriver 2.xx webdriver-manager downloaded files based on the https://chromedriver.storage.googleapis.com/ The versions from the download were formatted 2.xx. These did not map to versions of Chrome. To make semantic version comparisons, we would tack on a '.0' to user the semver node module to make comparisons. This assumption does not work with the new versioning for ChromeDriver 74 (74.0.3729.6). This is why it was not downloading the file. This change happened in approx August 2018. When this change happened fixes were added to the upcoming version of webdriver-manager 13. So why not use webdriver-manager@13? Some reasons why this won't work with Protractor 5.4.2: The fix was in for webdriver-manager 13 but Protractor 5.4.2 relies on webdriver-manager ^12.0.6. Installing another version of webdriver-manager might not work when resolving the downloaded files. This would not work when launching Protractor with direct connect (driverProviders/direct) or local since the update-config.json file is not created. There is a fix for this here: https://github.com/angular/webdriver-manager/pull/372 but probably will not be merged. How does webdriver-manager@12 download a max version of 74? For webdriver-manager@12, the max version is stored here: https://github.com/angular/webdriver-manager/blob/legacy/config.json#L5 If a Chrome releases 75, this should also be changed to version 75 in a pull request against the legacy branch. A: Try installing chromedriver v. 74.0.3729.6 (Chrome 74) LOCALLY AND GLOBALLY for the global installation run webdriver-manager update --versions.chrome 74.0.3729.6 for local installation run something like node ./node_modules/protractor/bin/webdriver-manager update --versions.chrome 74.0.3729.6 List of driver versions is here http://chromedriver.chromium.org/downloads Possibly you'll face this issue update protractor chrome driver to 74, see my comment there Let me know if you run into issues
{ "pile_set_name": "StackExchange" }
Q: How to burn an ISO file larger 4.7 GB onto a DVD I downloaded centos everything ISO which about 6.4GB in size however I could not write that ISO file onto a DVD using k3b tool as it is showing Blank dvd doesn't have enough space. I want to dual boot my computer one with Ubuntu and another one with Centos, For installing CENTOS i need to write that everything ISO on to the DVD which is of 4.7 GB in capacity and then go for installation. How should i ? A: It's just a matter of media. If the DVD ISO you have to write onto the media is bigger than 4.7 GB, you can use double-layer DVD if your writer is able to support this kind of DVD. Then you can put almost the double of 4.7 GB on a single double-layer DVD. Of course, if the ISO size exceeds the size limit of a double-layer DVD, you cannot do anything more with a DVD. A: There are two links to download CentOS 7 (the latest version) from the download site at centos.org. If you choose the first link by clicking the button that says DVD ISO you be asked to select a mirror and then download a 3.9GB CentOS ISO file that will fit nicely on a DVD. Clicking the other download button will download a bigger ISO that has a lot of additional packages that you don't need. Alternatively CentOS can also be written to an 8GB USB flash drive (or larger than 8GB) using UNetbootin from the default Ubuntu repositories. For general instructions about how to create a bootable USB stick using UNetbootin see this answer. UNetbootin has been dropped from the Ubuntu 18.04 repositories. When I tested the built-in Startup Disk Creator application as a UNetbootin replacement app with 3 non-*buntu live .iso images it worked in Ubuntu 18.04.
{ "pile_set_name": "StackExchange" }
Q: Complete information into Postfix logs I'm succesfully using Postfix on Debian to relay my internal e-mail and I am sending logs from the mail.log file to a Logstash instance, and I am showing them on a Kibana dashboards to look for not delivered and bounced e-mails. The problem I am having is that Postfix send information about delivered e-mails on multiple log lines, for example: Oct 9 18:19:58 mailserver postfix/smtpd[11513]: 7958440AA2: client=client.fqdn[123.123.123.123] Oct 9 18:19:59 mailserver postfix/cleanup[11518]: 7958440AA2: message-id=<> Oct 9 18:19:59 mailserver postfix/qmgr[26050]: 7958440AA2: from=<[email protected]>, size=841, nrcpt=1 (queue active) Oct 9 18:19:59 mailserver postfix/smtpd[11513]: disconnect from client.fqdn[123.123.123.123] helo=1 mail=1 rcpt=1 data=1 quit=1 commands=5 Oct 9 18:20:10 mailserver postfix/smtp[11519]: 7958440AA2: to=<[email protected]>, relay=relay.fqdn[111.111.111.111]:25, delay=12, delays=1/0.01/10/1.3, dsn=2.0.0, status=sent (250 2.0.0 Ok: queued as 1F2BF9679C4) Oct 9 18:20:10 mailserver postfix/qmgr[26050]: 7958440AA2: removed On Kibana I am displaying logs with the status= tag, to find out if the message is successfully delivered or not but in this way I am losing the information about the sender, which is displayed on another log line from Postfix. Is there a way to let Postfix insert the from= tag as well into the same log line with the success= tag? Or, is there a way to "merge" multiple logs into Logstash to have both from= and success= tags into a Kibana dashboard? A: You could use an aggregate plugin of Logstash to extract data from multiline input by queue-id. There are some examples for this approach available on Github
{ "pile_set_name": "StackExchange" }
Q: What liberation technique taught by Shree Ramana Maharshi? Ramana Maharshi was an enlightened master from the last century, what technique did he prescribe to know the self or become self realized? A: From the book Who am I. His technique name is Self inquiry. Que:10. How will the mind become quiescent? Ramana: By the inquiry ‘Who am I?’. The thought ‘who am I?’ will destroy all other thoughts, and like the stick used for stirring the burning pyre, it will itself in the end get destroyed. Then, there will arise Self-realization. Ques:11. What is the means for constantly holding on to the thought ‘Who am I?’ Ramana: When other thoughts arise, one should not pursue them, but should inquire: ‘To whom do they arise?’ It does not matter how many thoughts arise. As each thought arises, one should inquire with diligence, “To whom has this thought arisen?”. The answer that would emerge would be “To me”. Thereupon if one inquires “Who am I?”, the mind will go back to its source; and the thought that arose will become quiescent. With repeated practice in this manner, the mind will develop the skill to stay in its source. When the mind that is subtle goes out through the brain and the senseorgans, the gross names and forms appear; when it stays in the heart, the names and forms disappear. Not letting the mind go out, but retaining it in the Heart is what is called “inwardness” (antarmukha). Letting the mind go out of the Heart is known as “externalisation” (bahir-mukha). Thus, when the mind stays in the Heart, the ‘I’ which is the source of all thoughts will go, and the Self which ever exists will shine. Whatever one does, one should do without the egoity “I”. If one acts in that way, all will appear as of the nature of Siva (God).
{ "pile_set_name": "StackExchange" }
Q: setf doesn't work as I think I've just started leaning Common Lisp and I don't know why the code below returns 3: (progn (setq lista '(1 2)) (setq listb lista) (setf (nth 1 listb) 3) (nth 1 lista)) Can you help me, please? A: Setq does not copy things. After (setq listb lista), both names point to the same list. When you modify it using one name, it also changes under the other. If you want to create a copy, use copy-list, copy-tree, copy-alist, or copy-seq (see the CLHS). Also, don't modify literal data (things you quote (') are literal data). (let* ((list-a (list 1 2)) (list-b (copy-list list-a))) (setf (nth 1 list-b) 3) (nth 1 list-a))
{ "pile_set_name": "StackExchange" }
Q: MIPS (curiosity) faster way of clearing a register? What is the fastest way of clearing a register (=0) in MIPS assembly? Some examples: xor $t0, $t0, $t0 and $t0, $t0, $0 move $t0, $0 li $t0, 0 add $t0, $0, $0 Which is the most efficient? A: In many MIPS implementations, these ops will both compile to the same instruction, because typically 'mov $a, $b' is an idiom for or $a, $b, $0 and li $r, x is shorthand for ori $r, $0, x: move $t0, $0 li $t0, 0 and these will both take place on the same pipeline, being architecturally equivalent: xor $t0, $t0, $t0 and $t0, $t0, $0 and in every RISC implementation I've ever worked with, add is on the same pipe as xor/and/nor/etc. Basically, this is all particular to the implementation of a particular chip, but they all ought to be single clock. If the chip is out of order, li or and x, $0, $0 might be fastest because they minimize false dependencies on other registers.
{ "pile_set_name": "StackExchange" }
Q: Term for Internet or Texting Acronyms, e.g. LOL, IMHO, M8 What are the acronym, internet words like lol, brb, imho, etc., called? Is there such a term beyond acronym? I was wanting to tell someone that someone else was not familiar with the meme/internet jargon/acronym 'M8' (or mate), but couldn't think of a reasonable word to use. So, is there a term that would define these terms for how they are different than other, regular english 'SMS text'. Moreover, we find these terms more and more in the wild and not necessarily even on electronic devices, like on t-shirts or even spoken. If I e-mail the message, "I'll be leaving the office at 10, but then I'll brb." What would I call the 'brb' part of the message, apart from the rest? "He e-mailed his boss a message saying 'He'd be right back', but he decided using an [internet jargon] was acceptable." Update 02/01/2018 Although I have accepted an answer for now, I think it is inadequate, and that a word will eventually be coined to define these text terms. Until then... A: Generally, it's called "chat speak" or "text speak" as it originated in shorthand used when writing text messages and in chat rooms on the internet. The main Wikipedia article calls it SMS language but I've never heard that term before. SMS language or textese (also known as txt-speak, txtese, chatspeak, txt, txtspk, txtk, txto, texting language, txt lingo, SMSish, txtslang, txt talk) is a term for the abbreviations and slang commonly used with mobile phone text messaging, but sometimes used with other Internet-based communication such as email and instant messaging. The Wikipedia article includes lists of examples that include the ones you've listed in your question. Another source of information, NetLingo.com broadens the terms for this to include: a.k.a. Internet acronyms, text message jargon, abbreviations, initialisms, cyberslang, leetspeak, SMS code, textese Note that leetspeak (or just leet) is generally considered a separate entity from chat/text speak, as it uses more numerals and special suffixes and also encompasses things like ASCII art. LOL, notably, has its own Wikipedia article where it is defined as being internet slang: LOL or lol, an acronym for laugh(ing) out loud, or lots of laughs, is a popular element of Internet slang. It was first used almost exclusively on Usenet, but has since become widespread in other forms of computer-mediated communication and even face-to-face communication. It is one of many initialisms for expressing bodily reactions, in particular laughter, as text, including initialisms for more emphatic expressions of laughter such as LMAO ("laugh(ing) my ass off") and ROFL (or its older form ROTFL; "roll(ing) on the floor laughing"). Other unrelated expansions include the now mostly obsolete "lots of luck" or "lots of love" used in letter-writing.
{ "pile_set_name": "StackExchange" }
Q: Type based on generic (function parameter's type) I want to have a variable type based on function parameter type. I tried to use generics, but I still have some error. interface A { value: string; } interface B { value: number; } interface extA extends A { id?: string; } interface extB extends B { id?: number; } function foo<T extends A | B>(param: T) { const newParam: T extends A ? extA : extB = param; newParam.id = param.value; return newParam; } const a = { value: "1" } as A; const b = { value: 1 } as B; const resultA = foo(a); // resultA is "extA" not "extA | extB" const resultB = foo(b); // resultB is "extB" not "extA | extB" The code is made up, but it shows the idea. Based on the type of the function parameter param I want to use extended type of either of main types newParam. So if I choose a parameter of one of each type TS will know which type is being returned. How to achieve this? TS Playground A: If you don't need generics, then you can use function overloading in TS: function foo(param: A): extA; function foo(param: B): extB; function foo(param: A | B): extA | extB { const newParam: extA | extB = param; newParam.id = param.value; return newParam; } Full playground Type is correctly detected. But you should watch yourself in the function implementation - you return extA | extB what can be not valid with previous overloads (developer can make mistake in implementation or add new overload and forget about implementation). Example: function foo(param: A): extA; function foo(param: B): extB; function foo(param: A | B): extA | extB { const newParam: extB = { value: 3, id: 22 }; return newParam; // always returned only `extB` } const a = { value: "1" } as A; const b = { value: 1 } as B; const resultA = foo(a); const resultB = foo(b); resultA.value // type detected as string // (correct according to overloading) but implementation // returns always number what is correct according to its definition // but incorrect according to previous overload signatures - developer mistake Playground
{ "pile_set_name": "StackExchange" }
Q: xcode array of Arrays and UITableViews I am new to Xcode and Objective-C programming and need some help. I am looking to create a basic program for the iOS that uses hierarchal-data and 2 separate UITableViews. I want the second UITableView to be populated by an array that is passed between viewControllers, based on which cell/row is selected in the first UITableView. The program compiles but I get a SIGABRT error when running the program. Can someone help me fix the SIGABRT and pass the mainArray to the second tableView? Here is how far I have gotten. My code: ArrayTableViewController.h @interface arrayTableViewController : UITableViewController @property (nonatomic, strong) NSMutableArray *mainArray; @property (nonatomic, strong) NSMutableArray *secondArray; @property (nonatomic, strong) NSMutableArray *thirdArray; @end ArrayTableViewController.m #import "ArrayTableViewController.h" #import "table2.h" @implementation arrayTableViewController @synthesize mainArray, secondArray, thirdArray; -(void) viewDidLoad { [super viewDidLoad]; mainArray = [[NSMutableArray alloc] initWithObjects: secondArray, thirdArray, nil]; secondArray = [[NSMutableArray alloc] initWithObjects: @"123", @"456", nil]; thirdArray = [[NSMutableArray alloc] initWithObjects: @"78", @"90", nil]; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [mainArray count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } cell.textLabel.text = [mainArray objectAtIndex:[indexPath row]]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { table2 *table2Controller = [[table2 alloc] initWithNibName:@"table2" bundle:nil]; table2Controller.arrayForDisplay = [[mainArray objectAtIndex: [indexPath row]] objectAtIndex:1]; [self.navigationController pushViewController:table2Controller animated:YES]; } @end table2.h #import <UIKit/UIKit.h> @interface table2 : UITableViewController @property (nonatomic, strong) NSArray *arrayForDisplay; @end table2.m @implementation table3 @synthesize arrayForDisplay; Then the same cell configuration style that was used in ArrayTableViewController.m Edits: After making the necessary changes, when I run the program and select a row, I get a SIGABRT error at the following line. int main(int argc, char *argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([ArrayTableAppDelegate class])); } } What would you recommend? Should I turn off ARC and call my own releases? so that I can get to the second tableView? A: First mistake: In viewDidLoad method, you have created the mainArray with secondArray and thirdArray as elements even before you allocated those arrays. Second mistake: In cellForRowAtIndexPath: method: Check the line cell.textLabel.text = [mainArray objectAtIndex:[indexPath row]]; Actually the textLabel expects a NSString value to set. But you are setting an array. Edit: Set the value to textLabel as following: cell.textLabel.text = [[mainArray objectAtIndex:[indexPath row]] objectAtIndex:0]; Actually this will set the first value of the array. But that it depends on your requirement. Edit 2: arrayForDisplay is an array variable but you are setting a string variable to that in the statement table2Controller.arrayForDisplay = [[mainArray objectAtIndex: [indexPath row]] objectAtIndex:1]; Do it as follows: table2Controller.arrayForDisplay = [mainArray objectAtIndex: [indexPath row]];
{ "pile_set_name": "StackExchange" }
Q: How can I match against multiple regexes in Perl? I would like to check whether some string match any of a given set of regexes. How can I do that? A: Use smart matching if you have perl version 5.10 or newer! #! /usr/bin/env perl use warnings; use strict; use feature 'switch'; my @patterns = ( qr/foo/, qr/bar/, qr/baz/, ); for (qw/ blurfl bar quux foo baz /) { no warnings 'experimental::smartmatch'; print "$_: "; given ($_) { when (@patterns) { print "hit!\n"; } default { print "miss.\n"; } } } Although you don’t see an explicit ~~ operator, Perl's given/when does it behind the scenes: Most of the power comes from the implicit smartmatching that can sometimes apply. Most of the time, when(EXPR) is treated as an implicit smartmatch of $_, that is, $_ ~~ EXPR. (See Smartmatch Operator in perlop for more information on smartmatching.) “Smartmatch Operator” in perlop gives a table of many combinations you can use, and the above code corresponds to the case where $a is Any and $b is Array, which corresponds roughly to grep $a ~~ $_, @$b except the search short-circuits, i.e., returns quickly on a match rather than processing all elements. In the implicit loop then, we’re smart matching Any against Regex, which is $a =~ /$b/ Output: blurfl: miss. bar: hit! quux: miss. foo: hit! baz: hit! Addendum Since this answer was originally written, Perl’s designers have realized there were mistakes in the way smartmatching works, and so it is now considered an experimental feature. The case used above is not one of the controversial uses, nonetheless the code’s output would include given is experimental and when is experimental except that I added no warnings 'experimental::smartmatch';. Any use of experimental features involves some risk, but I’d estimate it being low likelihood for this case. When using code similar to the above and upgrading to a newer version of Perl, this is a potential gotcha to be aware of. A: From perlfaq6's answer to How do I efficiently match many regular expressions at once?, in this case the latest development version that I just updated with a smart match example. How do I efficiently match many regular expressions at once? (contributed by brian d foy) If you have Perl 5.10 or later, this is almost trivial. You just smart match against an array of regular expression objects: my @patterns = ( qr/Fr.d/, qr/B.rn.y/, qr/W.lm./ ); if( $string ~~ @patterns ) { ... }; The smart match stops when it finds a match, so it doesn't have to try every expression. Earlier than Perl 5.10, you have a bit of work to do. You want to avoid compiling a regular expression every time you want to match it. In this example, perl must recompile the regular expression for every iteration of the C loop since it has no way to know what C will be: my @patterns = qw( foo bar baz ); LINE: while( <DATA> ) { foreach $pattern ( @patterns ) { if( /\b$pattern\b/i ) { print; next LINE; } } } The C operator showed up in perl 5.005. It compiles a regular expression, but doesn't apply it. When you use the pre-compiled version of the regex, perl does less work. In this example, I inserted a C to turn each pattern into its pre-compiled form. The rest of the script is the same, but faster: my @patterns = map { qr/\b$_\b/i } qw( foo bar baz ); LINE: while( <> ) { foreach $pattern ( @patterns ) { if( /$pattern/ ) { print; next LINE; } } } In some cases, you may be able to make several patterns into a single regular expression. Beware of situations that require backtracking though. my $regex = join '|', qw( foo bar baz ); LINE: while( <> ) { print if /\b(?:$regex)\b/i; } For more details on regular expression efficiency, see I by Jeffrey Freidl. He explains how regular expressions engine work and why some patterns are surprisingly inefficient. Once you understand how perl applies regular expressions, you can tune them for individual situations. A: My go-to for testing a value against multiple regexes at once is Regexp::Assemble, which will "Assemble multiple Regular Expressions into a single RE" in a manner somewhat more intelligent and optimized than simply doing a join '|', @regexps. You are also able, by default, to retrieve the portion of the text which matched and, if you need to know which pattern matched, the track switch will provide that information. Its performance is quite good - in one application, I'm using it to test against 1700 patterns at once - and I have yet to need anything that it doesn't do.
{ "pile_set_name": "StackExchange" }
Q: How to show the step2 div when the user click in "go to step 2"? I have a multi step form using bootstrap and jQuery. The multi step form is for a user to buy a product. There are 4 steps: - Step 1 is for the user insert his info (name, email, etc) - Step 2 the user select the payment method - Step 3 the user introduces the payment data - Step 4 present an invoice for the user. When the user click "go to step 2" the url changes to "store.test/product/5/a-5/payment/paymentMethods" and the user remains in the same payment page, but how to change from step 1 to step 2 in the multi step form? The step1 html is like this: <div class="tab-pane fade show active clearfix" id="step1" role="tabpanel" aria-labelledby="home-tab"> <h6>User Info</h6> <form method="post" action="{{route('products.storeUserInfo', ['id' => $id, 'slug' => $slug])}}"> {{csrf_field()}} <div class="form-group font-size-sm"> <label for="name" class="text-gray">Name</label> <input type="text" required class="form-control" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}"> </div> <!-- other form fields --> <input type="submit" href="#step2" class="btn btn-primary btn float-right next-step" value="Go to step 2"/> </form> </div> In paymentcontroller I have the storeUserInfo to collect the user data introduced in step1 and redirect to the same page (My doubt is how to redirect to the same page but show the step2 div): public function storeUserInfo(Request $request, $id, $slug = null){ //dd($request); $request->validate([ 'name' => 'required|max:255|string', 'surname' => 'required|max:255|string', 'email' => 'required|max:255|string', ]); Session::put('name' , $request->name); Session::put('surname' , $request->surname); Session::put('email' , $request->email); return redirect(route('products.presentPaymentMethods',['id' => $id, 'slug' => $slug])); } public function presentPaymentMethods(Request $request, $id, $slug=null){ $productQuantities = Session::get('productQuantities'); return view('products.registration', ['productQuantities' => $productQuantities, 'id' => $id, 'slug' => $slug]); } Routes: Route::post('/product/{id}/{slug?}/payment/storeUserInfo', [ 'uses' => 'PaymentController@storeUserInfo', 'as' =>'products.storeUserInfo' ]); Route::get('/product/{id}/{slug?}/payment/paymentMethods', [ 'uses' => 'PaymentController@presentPaymentMethods', 'as' => 'products.presentPaymentMethods' ]); jQuery to navigatte between steps: <script type="text/javascript"> $(function(){ $('a.nav-link').on('show.bs.tab', function(e) { var $target = $(e.target); if (!divValid($('.nav-pills li a.active').prop('hash'))) { e.preventDefault(); } else if ($target.parent().hasClass('disabled')) { e.preventDefault(); } }); $(".next-step").click(function(e) { var $active = $('.nav-pills li a.active'); nextTab($active); }); $(".prev-step").click(function(e) { var $active = $('.nav-pills li a.active'); prevTab($active); }); function nextTab(elem) { elem.parent().next().removeClass('disabled').find('a.nav-link').click(); } function prevTab(elem) { elem.parent().prev().find('a.nav-link').click(); } }); A: Why don't you just collect all the data with js and post all at once to the server, I feel like you are going about this in a really complex way. Alternatively, collect your data for step one, post to server redirect the user to step 2, and repeat. e.g. Route::get('step1', 'step3@PaymentController')->name('step1'); Route::post('step1store', 'step1@PaymentController')->name('step1-store'); Route::get('step2', 'step2@PaymentController')->name('step2'); Route::post('step2store', 'step2@PaymentController')->name('step2-store'); Route::get('step3', 'step3@PaymentController')->name('step3'); Route::post('step3store', 'step3@PaymentController')->name('step3-store'); public function step1store(Request $request) { //process your data and store to db return redirect()->route('step2'); } public function step2store(Request $request) { //process your data and store to db return redirect()->route('step3'); } public function step3store(Request $request) { //process your data and store to db return redirect()->route('step4'); } I'm sure you get the idea. Personally, I would go with posting all the data at once verifying each page with ajax.
{ "pile_set_name": "StackExchange" }
Q: Beginner Programmer c++(local vs global variable declaration) I'm new to programming. I was trying to get the sum of the equation added to the previous value when I noticed some strange behavior. If I declare int result inside int main () then I get a blank answer, but if I declare int result outside int main () then I get these values: 6,11,16...91,96,101. It doesn't make sense to me since I have no other function. Why does this happen? #include<iostream> using namespace std; int main () { int y =1; int result; while (result <100) { result = y +5; cout << result << ","; y = result; } } A: Within a function, int result; declares a variable named result, but doesn't initialize it to any particular value. Until you assign it a value it could be anything, and the behavior when reading from it is undefined. Thus when you read its value in your while condition it could be anything; your loop may execute or it may not. You need to supply an initial value for result to make the behavior of your program well-defined: int result = 0; Unlike local variable, global variables are defined to be initialized to a default value when no initial value is explicitly provided, so when you read the value of result in your while condition, it is 0, and your loop executes.
{ "pile_set_name": "StackExchange" }
Q: Get line numbers with AddressSanitizer output? I'm trying to get AddressSanitizer to produce line numbers in its stack traces. I've tried on by a Mac and a Fedora 19 system and had similar results. Here is a simple program: #include <cstdio> #include <cstdlib> int main(int argc,char **argv) { char *buf = (char *)malloc(5); free(buf); puts("get ready"); buf[4] = '3'; puts("done"); return(0); } And I compile it: $ g++ -g -o x -fsanitize=address x.cpp And I run it (llvm-symbolizer is in my path): $ ASAN_SYMBOLIZER_PATH=`which llvm-symbolizer` ASAN_OPTIONS=symbolize=1 ./x get ready ================================================================= ==9309== ERROR: AddressSanitizer: heap-use-after-free on address 0x60040000dff4 at pc 0x40091f bp 0x7fff1b721140 sp 0x7fff1b721138 WRITE of size 1 at 0x60040000dff4 thread T0 #0 0x40091e in main (/raid/nfs_home/xv32/asan/x+0x40091e) #1 0x3304021b44 in __libc_start_main (/lib64/libc.so.6+0x3304021b44) #2 0x4007e8 (/raid/nfs_home/xv32/asan/x+0x4007e8) 0x60040000dff4 is located 4 bytes inside of 5-byte region [0x60040000dff0,0x60040000dff5) freed by thread T0 here: #0 0x7fe4ae58636a (/lib64/libasan.so.0+0x1536a) #1 0x4008d8 in main (/raid/nfs_home/xv32/asan/x+0x4008d8) #2 0x3304021b44 in __libc_start_main (/lib64/libc.so.6+0x3304021b44) previously allocated by thread T0 here: #0 0x7fe4ae58644a (/lib64/libasan.so.0+0x1544a) #1 0x4008c8 in main (/raid/nfs_home/xv32/asan/x+0x4008c8) #2 0x3304021b44 in __libc_start_main (/lib64/libc.so.6+0x3304021b44) SUMMARY: AddressSanitizer: heap-use-after-free ??:0 main Shadow bytes around the buggy address: 0x0c00ffff9ba0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c00ffff9bb0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c00ffff9bc0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c00ffff9bd0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c00ffff9be0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa =>0x0c00ffff9bf0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa[fd]fa 0x0c00ffff9c00: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c00ffff9c10: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c00ffff9c20: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c00ffff9c30: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c00ffff9c40: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa Shadow byte legend (one shadow byte represents 8 application bytes): Addressable: 00 Partially addressable: 01 02 03 04 05 06 07 Heap left redzone: fa Heap righ redzone: fb Freed Heap region: fd Stack left redzone: f1 Stack mid redzone: f2 Stack right redzone: f3 Stack partial redzone: f4 Stack after return: f5 Stack use after scope: f8 Global redzone: f9 Global init order: f6 Poisoned by user: f7 ASan internal: fe ==9309== ABORTING [r4 ~/asan 19:34:50]$ As you can see, I have symbols but no line numbers. How do I get line numbers? In answer to a question, here is the objdump -h x: $ objdump -h x x: file format elf64-x86-64 Sections: Idx Name Size VMA LMA File off Algn 0 .interp 0000001c 0000000000400238 0000000000400238 00000238 2**0 CONTENTS, ALLOC, LOAD, READONLY, DATA 1 .note.ABI-tag 00000020 0000000000400254 0000000000400254 00000254 2**2 CONTENTS, ALLOC, LOAD, READONLY, DATA 2 .note.gnu.build-id 00000024 0000000000400274 0000000000400274 00000274 2**2 CONTENTS, ALLOC, LOAD, READONLY, DATA 3 .gnu.hash 0000003c 0000000000400298 0000000000400298 00000298 2**3 CONTENTS, ALLOC, LOAD, READONLY, DATA 4 .dynsym 000001b0 00000000004002d8 00000000004002d8 000002d8 2**3 CONTENTS, ALLOC, LOAD, READONLY, DATA 5 .dynstr 00000141 0000000000400488 0000000000400488 00000488 2**0 CONTENTS, ALLOC, LOAD, READONLY, DATA 6 .gnu.version 00000024 00000000004005ca 00000000004005ca 000005ca 2**1 CONTENTS, ALLOC, LOAD, READONLY, DATA 7 .gnu.version_r 00000020 00000000004005f0 00000000004005f0 000005f0 2**3 CONTENTS, ALLOC, LOAD, READONLY, DATA 8 .rela.dyn 00000018 0000000000400610 0000000000400610 00000610 2**3 CONTENTS, ALLOC, LOAD, READONLY, DATA 9 .rela.plt 000000d8 0000000000400628 0000000000400628 00000628 2**3 CONTENTS, ALLOC, LOAD, READONLY, DATA 10 .init 0000001a 0000000000400700 0000000000400700 00000700 2**2 CONTENTS, ALLOC, LOAD, READONLY, CODE 11 .plt 000000a0 0000000000400720 0000000000400720 00000720 2**4 CONTENTS, ALLOC, LOAD, READONLY, CODE 12 .text 00000224 00000000004007c0 00000000004007c0 000007c0 2**4 CONTENTS, ALLOC, LOAD, READONLY, CODE 13 .fini 00000009 00000000004009e4 00000000004009e4 000009e4 2**2 CONTENTS, ALLOC, LOAD, READONLY, CODE 14 .rodata 000000bc 0000000000400a00 0000000000400a00 00000a00 2**5 CONTENTS, ALLOC, LOAD, READONLY, DATA 15 .eh_frame_hdr 00000044 0000000000400abc 0000000000400abc 00000abc 2**2 CONTENTS, ALLOC, LOAD, READONLY, DATA 16 .eh_frame 00000134 0000000000400b00 0000000000400b00 00000b00 2**3 CONTENTS, ALLOC, LOAD, READONLY, DATA 17 .preinit_array 00000008 0000000000600d98 0000000000600d98 00000d98 2**3 CONTENTS, ALLOC, LOAD, DATA 18 .init_array 00000010 0000000000600da0 0000000000600da0 00000da0 2**3 CONTENTS, ALLOC, LOAD, DATA 19 .fini_array 00000010 0000000000600db0 0000000000600db0 00000db0 2**3 CONTENTS, ALLOC, LOAD, DATA 20 .jcr 00000008 0000000000600dc0 0000000000600dc0 00000dc0 2**3 CONTENTS, ALLOC, LOAD, DATA 21 .dynamic 00000230 0000000000600dc8 0000000000600dc8 00000dc8 2**3 CONTENTS, ALLOC, LOAD, DATA 22 .got 00000008 0000000000600ff8 0000000000600ff8 00000ff8 2**3 CONTENTS, ALLOC, LOAD, DATA 23 .got.plt 00000060 0000000000601000 0000000000601000 00001000 2**3 CONTENTS, ALLOC, LOAD, DATA 24 .data 00000070 0000000000601060 0000000000601060 00001060 2**5 CONTENTS, ALLOC, LOAD, DATA 25 .bss 00000008 00000000006010d0 00000000006010d0 000010d0 2**2 ALLOC 26 .comment 00000058 0000000000000000 0000000000000000 000010d0 2**0 CONTENTS, READONLY 27 .debug_aranges 00000050 0000000000000000 0000000000000000 00001128 2**0 CONTENTS, READONLY, DEBUGGING 28 .debug_info 00001041 0000000000000000 0000000000000000 00001178 2**0 CONTENTS, READONLY, DEBUGGING 29 .debug_abbrev 0000038e 0000000000000000 0000000000000000 000021b9 2**0 CONTENTS, READONLY, DEBUGGING 30 .debug_line 00000239 0000000000000000 0000000000000000 00002547 2**0 CONTENTS, READONLY, DEBUGGING 31 .debug_str 00000a9a 0000000000000000 0000000000000000 00002780 2**0 CONTENTS, READONLY, DEBUGGING $ A: Answer posted at How do I get line numbers in the debug output with clang's -fsanitize=address?. You need to use the llvm-symbolizer or addr2line
{ "pile_set_name": "StackExchange" }
Q: Linux tmpfs write speed slower than RAM speed I have a HPE ProLiant DL360 Gen9 server, specs are: CPU: Intel Xeon 2 CPUs E5-2687W v3 @ 3.10GHz, 25MB L3 cache, 10 cores ea RAM: 8x 32GB PC4-17000 DDR4 2133MHz CAS-15 1.2V SDRAM DIMM (256 GB total) (full server specs here) The server is running CentOS 7.2 with kernel 3.10.0-327.36.3.el7.x86_64. I mounted a tmpfs ramdisk on the server using the following entry in /etc/fstab: tmpfs /ramdisk tmpfs noauto,user 0 0 To test writing to this ramdisk, I then run the following command: time sh -c "dd if=/dev/zero of=/ramdisk/120GB_testfile bs=4k count=30000000 && sync" It reports that it wrote 122,880,000,000 bytes in 58.857s, which is a write speed of 1991 MiB/sec. Considering that the write speed of this memory is 17GB/sec (according to this description of memory data rates), I am surprised by the considerably lower rate when writing to my tmpfs ramdisk. Can anyone explain the disparity, and suggest another way to write to a file in memory that is faster? Thanks. UPDATE I disabled vm.swappiness, but that yielded no benefit (1712 MiB/sec). I tried increasing the block size as well (bs=256k count=468750), but again, not much of an effect (2087 MiB/sec). A: There's more going on than just putting data in RAM when you're using an in-memory filesystem. You still have to handle the data structures associated with the file, including tracking where in memory all the allocations for it are. Writing this information takes time too (in particular, for the testing you're doing, your file size is being updated on every write, which immediately doubles the number of places data is changing in memory). Also, allocating memory is extremely slow. In fact, it's about one of the slowest things you can do on most systems that doesn't involve I/O, with the only significantly slower thing being creating a new thread or process. Tools like ramspeed pre-allocate all the memory they will use right when they start up, so they can test the actual memory performance. In comparison, tmpfs has no idea how big of a file you are going to be creating, so it has to allocate everything on-demand, and does so in chunks no bigger than the dd block size (I think it caps out at 64k, but I'm not sure). Because of this, you have overhead in every block for allocating memory to store that block in.
{ "pile_set_name": "StackExchange" }
Q: Ball Collision sticking to a static ball I have this setup where balls are colliding, when all have a velocity it works great, but now I'm trying to make them collide with an static one, so I've made a staticBall where the velocity is always 0 and can't be set. But when a collision occurs, the ball (not static) sticks to the static one. but I don't know why. What am I doing wrong? here is the code used for making them bounce. Any other remarks to the code is welcome ;) BallBase: public abstract class BallBase { protected Vector _vel; public virtual Vector Vel { get { return _vel; } set { _vel = value; } } public Point Pos { get; set; } public double Rad { get; set; } public abstract void Tick(double deltaTime, double width, double height); public abstract Shape Paint(); } Ball: public class Ball : BallBase { public Ball(Point pos, double rad, Vector vel) { Pos = pos; Rad = rad; _vel = vel; } public override Vector Vel { get { return _vel; } set { _vel = value; } } public override Shape Paint() { return new Ellipse { Fill = Brushes.DarkBlue, Width = Rad*2, Height = Rad*2, Margin = new Thickness(Pos.X - Rad, Pos.Y - Rad, 0, 0) }; } public override void Tick(double deltaTime, double width, double height) { Pos = new Point(Pos.X + Vel.X*deltaTime/1000, Pos.Y + Vel.Y*deltaTime/1000); if ((Pos.X + Rad) > width && Vel.X > 0) Vel = new Vector(Vel.X*-1, Vel.Y); if ((Pos.Y + Rad) > height && Vel.Y > 0) Vel = new Vector(Vel.X, Vel.Y*-1); if ((Pos.X - Rad) < 0 && Vel.X < 0) Vel = new Vector(Vel.X*-1, Vel.Y); if ((Pos.Y - Rad) < 0 && Vel.Y < 0) Vel = new Vector(Vel.X, Vel.Y*-1); } } StaticBall: public class StaticBall : BallBase { public StaticBall(Point pos, double rad) { Pos = pos; Rad = rad; _vel = new Vector(0, 0); } public override Vector Vel { get { return _vel; } set { } } public override Shape Paint() { return new Ellipse { Fill = Brushes.Gray, Width = Rad*2, Height = Rad*2, Margin = new Thickness(Pos.X - Rad, Pos.Y - Rad, 0, 0) }; } public override void Tick(double deltaTime, double width, double height) {} } Collision Handeling: private void HandleCollisions() { for (int i = 0; i < _ball.Count; ++i) { for (int j = i + 1; j < _ball.Count; ++j) //let op j=i+1 { // calculate distance between centers of balls Vector diff = _ball[i].Pos - _ball[j].Pos; double distance = diff.Length; // calculate sum of Radius double sumRadii = _ball[i].Rad + _ball[j].Rad; // check collision if dist<sum of diameters if (distance < sumRadii) Bounce(i, j); } } } private void Bounce(int ball1, int ball2) { // vector that connects between both balls Vector centerNorm = (_ball[ball1].Pos - _ball[ball2].Pos); centerNorm.Normalize(); // Project the velocity vector on the centerNorm Vector projVelocity1 = Dot(centerNorm, _ball[ball1].Vel)*centerNorm; Vector projVelocity2 = Dot(centerNorm, _ball[ball2].Vel)*centerNorm; // if in same direction if (Dot(projVelocity1, projVelocity2) > 0) { // if the first one is moving faster than the second, don't interfere // first one is identified by dot with centerNorm if (Dot(centerNorm, projVelocity1) > 0) { if (projVelocity1.Length > projVelocity2.Length) return; } else if (projVelocity1.Length < projVelocity2.Length) return; } // they are not moving in the same direction else if (Dot(centerNorm, projVelocity1) > 0) return; // calculate tangetnt Vector tangentVelocity1 = _ball[ball1].Vel - projVelocity1; Vector tangentVelocity2 = _ball[ball2].Vel - projVelocity2; // New vel is sum own tangent and projection of the other Vector newVelocity1 = tangentVelocity1 + projVelocity2; Vector newVelocity2 = tangentVelocity2 + projVelocity1; // collision with static ball is like colliding with a wall if (_ball[ball1].GetType() == typeof (StaticBall)) newVelocity2 = tangentVelocity2 - _ball[ball2].Vel; else if (_ball[ball2].GetType() == typeof (StaticBall)) newVelocity1 = tangentVelocity1 - _ball[ball1].Vel; // assign _ball[ball1].Vel = newVelocity1; _ball[ball2].Vel = newVelocity2; } EDIT: added solution, found by Tariks answer A: Assuming you have a regular ball (non-static) at rest, a ball that would collide with it with a tangent velocity of zero and a normal velocity v would cause the colliding ball to come at rest and the ball that was at rest to move with velocity v in the same direction as the colliding ball. In the case of the "static" ball, the colliding ball stops and the static ball does not move either. They stick. To correct this, the static ball should be handled like a wall or more appropriately a column on which other balls bounce. The tangent velocity should be conserved but the normal velocity v should become -v.
{ "pile_set_name": "StackExchange" }
Q: how to parse float in javascript like c# float? I am newbie to javascript, forgive me if i ask this kind of question in c# I have : (float)3772/32767 = 0.115115821 but in javascript i have : 3772/32767 = 0.11511581774346141 I heard there is a function parseFloat but it does not fix my problem I want the result to be like the c# float result, because in javascript side it brings some noise to my final data, how to cast like a c# float ? A: You can use the toFixed() or toPrecision() methods to change the precision of float-numbers: let number = 3772/32767; console.log(number); console.log(number.toFixed(7)); console.log(number.toPrecision(8));
{ "pile_set_name": "StackExchange" }
Q: Why does Dumbledore beg Snape in HBP? When Snape climbs the steps up to the Astronomy Tower in Half-Blood Prince (The Lightning-Struck Tower chapter): But somebody else had spoken Snape's name, quite softly. "Severus..." The sound frightened Harry beyond anything he had experienced all evening, Dumbledore was pleading. And then “Severus . . . please . . .” Was this to keep up the illusion, or was there unfinished business, the plan was not ready that night? Did Dumbledore not want Harry to see? A: Snape was Dumbledore's double agent from the beginning and the plan was for Snape to kill Dumbledore (who was dying anyway) to prove his loyalty to Voldemort, which would result in him getting closer. Snape was against this plan but had reluctantly agreed. When the time came for Snape to actually kill Dumbledore he hesitated, which is why Dumbledore pleaded with him. Not to spare his life, but to do his part in the plan and kill Dumbledore. A: The other answers here aren't wrong. But they don't contain the (whole) correct answer. Namely: Dumbledore was scared of Greyback. This is what causes Dumbledore to plead with Snape. He knew that he was going to die one way or another. He had embraced death and wasn't scared of it. But he was worried that he might die at the hands of another Death Eater (like Greyback) who would cause his death to be drawn-out and traumatic. "You alone know whether it will harm your soul to help an old man avoid pain and humiliation," said Dumbledore. "I ask this one, great favour to you, Severus, because death is coming for me as surely as the Chudley Cannons will finish bottom of this year's league. I confess I should prefer a quick, painless exit to the protracted and messy affair it will be if, for instance, Greyback is involved - I hear Voldemort has recruited him? Or dear Bellatrix, who likes to play with her food before she eats it." His tone was light but his blue eyes pierced Snape as they had frequently pierced Harry, as though the soul they discussed was visible to him. At last Snape gave another curt nod. (Deathly Hallows, Chapter 33, The Prince's Tale). Note that Dumbledore wants to avoid pain and humiliation and is specifically worried about Greyback and Bellatrix. When he's disarmed on the Astronomy Tower Dumbledore knows that his time must be up. Either Snape will kill him or one of the other Death Eaters will. Bellatrix isn't there to do it but, as he had feared, Greyback is. "Is that you, Fenrir?" asked Dumbledore. "That's right," rasped the other. "Pleased to see me, Dumbledore?" "No, I cannot say that I am..." Fenrir Greyback grinned, showing pointed teeth. Blood trickled down his chin and he licked his lips slowly, obscenely. "But you know how much I like kids, Dumbledore." "Am I now to take it that you are attacking even without the full moon now? This is most unusual...you have developed a taste for human flesh that cannot be satisfied once a month?" "That's right," said Greyback. "Shocks you, that, doesn't it, Dumbledore? Frightens you?" "Well, I cannot pretend it does not disgust me a little," said Dumbledore. [...] And he raised a yellow fingernail and picked at his front teeth, leering at Dumbledore. "I could do you for afters, Dumbledore..." (Half-Blood Prince, Chapter 27, The Lightning-Struck Tower). Dumbledore was brave enough to stand up to Greyback. He wasn't going to betray his fear openly in front of the Death Eaters. But that doesn't mean he wasn't scared. He is unarmed and defenceless. Greyback is demonstrating his very real desire to rip him to pieces. That's not a pretty death, as Dumbledore himself says in the earlier quote. Although he also cared about saving Draco's soul, as Dave Johnson says, he is really speaking out of self-interest here. Snape is his one way out of a grisly, painful death. Yet Snape was unwilling to kill Dumbledore - perhaps out of love/respect for Dumbledore and perhaps because killing someone is simply a big deal (Snape has to summon the will to go through with Dumbledore's request). So Dumbledore pleads with him to keep his word and finish him off - knowing the fate that awaits him if Snape should fail. A: It was revealed that the plan the entire time was for Snape to kill Dumbledore, because Dumbledore was foolish when handling one of the Horcruxes, and thus dying anyway. Having Snape be the one to kill Dumbledore ensured that Voldemort would trust Snape that much more. Also, more specific to the question, Dumbledore was pleading because above all else, Dumbledore did not want Draco to be the one to kill him. Dumbledore very much believed that Draco could be saved, and knew that killing someone fractures your soul. In fact, that is specifically what must be done to create a Horcrux: By an act of evil -- the supreme act of evil. By committing murder. Killing rips the soul apart. The wizard intent upon creating a Horcrux would use the damage to his advantage: he would encase the torn portion. ...
{ "pile_set_name": "StackExchange" }
Q: "how did" vs "how" + past tense What is more correct: How did you solve the problem? or How you solved the problem? When I use the first variant, people tend to skip the initial word and treat is as if I asked "Did you...". Why? A: In a direct question, auxiliary do must be used, to the correct sentence is: How did you solve the problem? However, if the question is about the subject, then there is no auxiliary do: Who solved the problem? On a side note, in an indirect question or if it is not a question, you don't use the auxiliary do, either: Now tell me how you solved the problem. Could you tell us how you solved the problem? In a negative statement, however, you negate the verb with do not: Tell us why you did not solve the problem.
{ "pile_set_name": "StackExchange" }
Q: How to make fixed navbar top like w3school i want to make top fixed navbar like w3school.com? when i scroll down, the top navbar will fixed and the logo are not. how to do that with using bootstrap css framewok? is that only can use with w3.css ? i doubt about it. thank you! #logo { text-align: center;} <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <body> <div id="logo"> <img src="http://lorempicsum.com/futurama/350/200/1"/> </div> <div id="nav"> <ul class="nav nav-tabs navbar-fixed-top"> <li><a href="...">Fixed</a></li> <li><a href="...">Fixed</a></li> <li><a href="...">Fixed</a></li> <li><a href="...">Fixed</a></li> <li><a href="...">Fixed</a></li> <li><a href="...">Fixed</a></li> </ul> </div> <p> i want the navbar fixed like w3school.com when it the scroll down until reach the image the navbar will fixed. sorry for bad english. visit w3school to see the navbar fixed top </p> A: This is what u want: <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Navbar like w3schools</title> <script> jQuery(document).ready(function($) { // Fixa navbar ao ultrapassa-lo var navbar = $('#navbar-main'), distance = navbar.offset().top, $window = $(window); $window.scroll(function() { if ($window.scrollTop() >= distance) { navbar.removeClass('navbar-fixed-top').addClass('navbar-fixed-top'); $("body").css("padding-top", "70px"); } else { navbar.removeClass('navbar-fixed-top'); $("body").css("padding-top", "0px"); } }); }); </script> <style> @media screen and (max-width: 768px){ .man{ display:none; } } body { overflow-x: hidden;} </style> </head> <body> <div class="row"> <div style="font-weight:bold;font-size:35px;font-family:cursive;padding:5px;left:15px" class="col-xs-12 col-sm-offset-1 col-sm-4">w3schools<span style="color:green">.com</span></div> <div style="font-weight:lighter;font-size:25px;padding:5px;top:12px" class="man col-xs-12 col-sm-offset-1 col-sm-6">The world's largest web developer site</div> </div> <nav id="navbar-main" class="navbar navbar-inverse"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display--> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li> <li><a href="#">Link</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li><a href="#">Separated link</a></li> <li role="separator" class="divider"></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> <form class="navbar-form navbar-left" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Link</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <main class="container"> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id voluptatum sequi sunt asperiores eius, qui saepe tempore aliquam debitis distinctio officia optio unde perferendis fugiat sint quia consequuntur, placeat sed!</p> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id voluptatum sequi sunt asperiores eius, qui saepe tempore aliquam debitis distinctio officia optio unde perferendis fugiat sint quia consequuntur, placeat sed!</p> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id voluptatum sequi sunt asperiores eius, qui saepe tempore aliquam debitis distinctio officia optio unde perferendis fugiat sint quia consequuntur, placeat sed!</p> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id voluptatum sequi sunt asperiores eius, qui saepe tempore aliquam debitis distinctio officia optio unde perferendis fugiat sint quia consequuntur, placeat sed!</p> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id voluptatum sequi sunt asperiores eius, qui saepe tempore aliquam debitis distinctio officia optio unde perferendis fugiat sint quia consequuntur, placeat sed!</p> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id voluptatum sequi sunt asperiores eius, qui saepe tempore aliquam debitis distinctio officia optio unde perferendis fugiat sint quia consequuntur, placeat sed!</p> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id voluptatum sequi sunt asperiores eius, qui saepe tempore aliquam debitis distinctio officia optio unde perferendis fugiat sint quia consequuntur, placeat sed!</p> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id voluptatum sequi sunt asperiores eius, qui saepe tempore aliquam debitis distinctio officia optio unde perferendis fugiat sint quia consequuntur, placeat sed!</p> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id voluptatum sequi sunt asperiores eius, qui saepe tempore aliquam debitis distinctio officia optio unde perferendis fugiat sint quia consequuntur, placeat sed!</p> </main> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Graph with exactly 2 Minimum Spanning Trees Say that a graph, $G = (V, E)$ has 2 minimum spanning trees (MSTs). Given this condition stipulated, prove that any cycle formed by all the edges in both the MSTs (i.e., the union of the edges in of the 2 MSTs) that at minimum, 2 of the edges in the set which is the union of the edges have equal weight. Also show that either this edge is the largest weight in the cycle, or not the largest weight in the cycle. Overall am pretty stuck on this question. My initial thoughts are the following: In any graph with more than 1 MST, clearly this means that the edge weights can't be distinct, otherwise there wouldn't be multiple MSTs. Also the graph $G$ must contain cycles, otherwise, it wouldn't have multiple MSTs. My idea for proving that any cycle formed by the union of the edges of the two MSTs would be that in $MST_1$ there is some edge, $e$ that is not in $MST_2$ and there is also some edge $f$ that is not in $MST_1$. Using the cut property if $e$ was not placed in $MST_2$ and $f$ was not placed in $MST_1$ then then we have that the weight of $f$, and $e$, $w(f) = w(e)$. Having trouble formalizing this though, and wondering if its actually a correct deduction. I feel that it makes sense given some examples and drawing, but not quite certain that's actually true. Then from there I felt that there had to be some node, $z$ such that $z$ had 2 edges with the same weights, and when we combine the edges from $MST_1$ and $MST_2$ we end up with both the edges from $z$ forming a cycle, and the edges are the same weights, so we know at least 2 of the edges form a cycle... Or the union of the edges could form a cycle graph itself which would then show that the 2 edges with the same weights are part of a cycle, I think? Is this somewhat on the right track? Is there some sort of condition for a graph, $G$, in order for it to have exactly 2 MSTs? Or is there some property I'm missing? If someone could please provide a bit of guidance in the right direction, it would be extremely appreciated. Thanks. A: Lemma: Let $C$ be a cycle of $G$ that contains an unique edge $e$ of maximum weight. Edge $e$ does not belong to any MST of $G$. Proof: Suppose that a MST $T^* = (V, E^*)$ of $G$ contains $e = (u,v)$. Root $T^*$ in $u$ and let $f$ be any edge of $C \setminus E^*$ that has exactly one endpoint in the subtree of $T^*$ rooted in $v$ (this edge always exists since $C \setminus \{ e \}$ is a path from $v$ to $u$ that avoids $e$). The edge $f$ closes a fundamental cycle containing $e$ and is such that $w(f) < (e)$. Then $(V, (E^* \setminus \{e\}) \cup \{ f \}$) is a spanning tree of $G$ that weighs less than $T^*$. This is a contradiction. $\square$ Let $T_1 = (V, E_1)$ and $T_2 = (V, E_2)$ be two distinct MSTs of $G$. Let $C$ be a cycle in $(V, E_1 \cup E_2$). Let $M = \arg\max_{e \in C} w(e)$. If $|M|>1$ we are done. Suppose then that $M = \{ e \}$. By the above lemma, $e$ is the unique heaviest edge of $C$ and hence it cannot belong to any MST of $G$. This is a contradiction since $e$ must belong to at least one of $E_1$ and $E_2$.
{ "pile_set_name": "StackExchange" }
Q: How can i check double array for uniqueness? For example we have String [][] doubleArray = {{"a","1"},{"b","3"},{"a","1"},{"c","1"}};. How can i create a new array with only uniqueness subarrays : {{"a","1"},{"b","3"},{"c","1"}} What i tryed : Set <String []> uniq = new HashSet<String []>(Arrays.asList(doubleArray)); But Java doesnt see the difference between {"a","1"} and {"a","1"} , so uniq returns me set of all subarrays of doubleArray, including clones. A: You can use Map like this: String [][] doubleArray = {{"a","1"},{"b","3"},{"a","1"},{"c","1"}}; Map<String, String> map = new HashMap<>(); for (String[] strings : doubleArray) { map.put(strings[0], strings[1]); } System.out.println("map = " + map); The result: map = {a=1, b=3, c=1}
{ "pile_set_name": "StackExchange" }
Q: Add nodes to binary search tree c++ I am building a binary search tree. Now I am having a problem with adding a node to the tree. void BinaryTree::add(int value, Node* node) { if(!node) node = new Node(value); else if(node->key < value) this->add(value, node->rightNode); else if(node->key > value) this->add(value, node->leftNode); } This code does not seem to work when I call: BinaryTree test; test.add(4, test.root); test.add(1, test.root); test.add(5, test.root); test.add(2, test.root); test.add(3, test.root); test.add(7, test.root); test.add(6, test.root); After the first add call, the root of the tree 'test' is still empty. How shall I change the code so that it will be updated when I call add and the node goes to the correct place of the tree? Thank you very much! A: You are passing the Node * by value here: void BinaryTree::add(int value, Node* node) { One solution is to pass by reference instead: void BinaryTree::add(int value, Node *& node) { ^ If you pass by value the function is just receiving a copy of the Node * and so any modification to it will not be reflected back in the calling code. Also you might want to think about what happens when value is equal to the key.
{ "pile_set_name": "StackExchange" }
Q: Create SOAP XML REQUEST from selected dataframe columns in Scala Is there a way to create an XML SOAP REQUEST by extracting a few columns from each row of a dataframe ? 10 records in a dataframe means 10 separate SOAP XML REQUESTs. How would you make the function call using map now? A: You can do that by applying a map function to the dataframe. val df = your dataframe df.map(x => convertToSOAP(x)) // convertToSOAP is your function. Putting up an example based on your comment, hope you find this useful. case class emp(id:String,name:String,city:String) val list = List(emp("1","user1","NY"),emp("2","user2","SFO")) val rdd = sc.parallelize(list) val df = rdd.toDF df.map(x => "<root><name>" + x.getString(1) + "</name><city>"+ x.getString(2) +"</city></root>").show(false) // Note: x is a type of org.apache.spark.sql.Row Output will be as follows : +--------------------------------------------------+ |value | +--------------------------------------------------+ |<root><name>user1</name><city>NY</city></root> | |<root><name>user2</name><city>SFO</city></root> | +--------------------------------------------------+
{ "pile_set_name": "StackExchange" }
Q: Replace a part of a string with mySQL - how to remove middle initial from first name field I feel like I'm missing something easy here but... If I have the following data in a mySQL table (users.fName): -------------- | Jason M. | -------------- | Eric | -------------- | Tim S | -------------- | Peggy Sue | -------------- And I want to end up with: -------------- | Jason | -------------- | Eric | -------------- | Tim | -------------- | Peggy Sue | -------------- I figure I have to eliminate the . after Jason M. (which I can do easily enough with UPDATE users SET fName = REPLACE(fName, ".", ""); ) but how can I eliminate the M and S but leave Sue? I know SUBSTRING_INDEX can get parts of the field and I can use something like SELECT SUBSTRING_INDEX(fName, ' ', -1), LENGTH(SUBSTRING_INDEX(fName, ' ', -1)) FROM users to get the lenght of the second part of the string but I'm not sure how to update the field to the first part of the string only of the second part is only one character long. UPDATE The answer form @Dan got me what I needed once I made one change to his query. The updated query is: SELECT `fName`, SUBSTRING_INDEX(`fName`, ' ', -1) AS MiddleInitial FROM `users` WHERE TRIM(`fName`) LIKE '%.' AND length(`fName`)> 4 OR length(SUBSTRING_INDEX(`fName`, ' ', -1)) = 1; The last AND becomes an OR and all worked. A: I had a similar situation and used a where clause to only select names with a space somewhere in the field. Further, I checked that what I expected to be a middle initial was indeed only one characters long with length(SUBSTRING_INDEX(First, ' ', -1)) = 1. SELECT `First`, SUBSTRING_INDEX(`First`, ' ', -1) AS MiddleInitial FROM YourTable WHERE trim(`First`) LIKE '%.' AND length(`First`)> 4 AND length(SUBSTRING_INDEX(`First`, ' ', -1)) = 1; Look over the results of the select before running the update but this should limit your query to only initials and leave names like Billy Bob alone.
{ "pile_set_name": "StackExchange" }
Q: Why does findcontrol need unique id, when I have given it the row to scan The code public partial class Table_Traversing : System.Web.UI.Page { Table table1 = new Table(); Button button1 = new Button(); protected void Page_Load(object sender, EventArgs e) { for (int adding_rows = 0; adding_rows < 4; adding_rows++) { TableRow table_row1 = new TableRow(); TableCell table_cell1 = new TableCell(); TableCell table_cell2 = new TableCell(); Label The_text = new Label(); CheckBox checkmate = new CheckBox(); The_text.Text = "This is the text :-)"; checkmate.ID = "checkmate"; table_cell2.Controls.Add(checkmate); table_cell1.Controls.Add(The_text); table_row1.Controls.AddAt(0, table_cell1); table_row1.Controls.AddAt(1, table_cell2); table1.Rows.Add(table_row1); } button1.Text = "click me to export the value"; form1.Controls.AddAt(0, table1); form1.Controls.AddAt(1, button1); button1.Click += new EventHandler(button1_Click); } void button1_Click(object sender, EventArgs e) { CheckBox check_or_not = new CheckBox(); for (int i = 0; i < table1.Rows.Count; i++) { check_or_not = (CheckBox)table1.Rows[i].FindControl("checkmate"); Response.Write(check_or_not.Checked.ToString()); } } } The error Multiple controls with the same ID 'checkmate' were found. FindControl requires that controls have unique IDs. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Web.HttpException: Multiple controls with the same ID 'checkmate' were found. FindControl requires that controls have unique IDs. A: You added the checkbox to the cell, not the row: table_cell2.Controls.Add(checkmate); Hence - one row has multiple cells with id "checkmate": E.g <tr id="somerow"> <td><input type="checkbox" id="checkmate"/></td> <td><input type="checkbox" id="checkmate"/></td> </tr> So within the row "somerow", there are multiple checkboxes with id "checkmate". Your code to add the checkboxes seemingly looks like you're only adding one though - so it must be something you've missed. Try removing the FindControl code and see what actual HTML get's rendered.
{ "pile_set_name": "StackExchange" }
Q: returns 403(forbidden) when using authentication scheme in .net core I am doing authentication in my web application with Jwt Security Tokens and custom authentication scheme. 1) I am generating tokens when user login 2)I created authentication handler where I validates token for all requests //Authentication Handler public class CustomAuthenticationHandler : AuthenticationHandler<CustomAuthenticationOptions> { public CustomAuthenticationHandler( IOptionsMonitor<CustomAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { } protected override Task<AuthenticateResult> HandleAuthenticateAsync() { try { Exception ex; var key = Request.Headers[Options.HeaderName].First(); if (!IsValid(key, out ex)) { return Task.FromResult(AuthenticateResult.Fail(ex.Message)); //filterContext.Result = new CustomUnauthorizedResult(ex.Message); } else { AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(),new AuthenticationProperties(),this.Scheme.Name); return Task.FromResult(AuthenticateResult.Success(ticket)); } } catch (InvalidOperationException) { return Task.FromResult(AuthenticateResult.Fail("")); } } } public static class CustomAuthenticationExtensions { public static AuthenticationBuilder AddCustomAuthentication(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<CustomAuthenticationOptions> configureOptions) { return builder.AddScheme<CustomAuthenticationOptions, CustomAuthenticationHandler>(authenticationScheme, displayName, configureOptions); } } and here is my startup.cs public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Person>()); services.AddTransient<IRepositoryWrapper, RepositoryWrapper>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddAuthentication(options=> { options.DefaultScheme = "CustomScheme"; options.DefaultAuthenticateScheme = "CustomScheme"; options.DefaultChallengeScheme = "CustomScheme"; }).AddCustomAuthentication("CustomScheme", "CustomScheme", o => { }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); loggerFactory.AddDebug(LogLevel.Information); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseAuthentication(); app.UseHttpsRedirection(); app.UseMvc(); } } and here I used authentication scheme [Authorize(AuthenticationSchemes ="CustomScheme")] [ApiController] [Route("api/controller")] public class UserController : BaseController { public UserController(IRepositoryWrapper repository) : base(repository) { } [HttpGet] public IEnumerable<Users> Get() { return _repository.Users.FindAll(); } } When I calling the api from postman with valid token it returns 403 error. Please help to solve this...!! A: I found the solution. I used CustomAuthenticationMiddle instead of AuthenticationHandler public class CustomAuthenticationMiddleware { private readonly RequestDelegate _next; public CustomAuthenticationMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { try { Exception ex; var key = context.Request.Headers["Authorization"].First(); if (!IsValid(key)) { //logic for authentication } else { await _next.Invoke(context); } } catch (InvalidOperationException) { context.Response.StatusCode = 401; //Unauthorized return; } } private bool IsValid(string key) { //Code for checking the key is valid or not } } and I added following in startup.cs app.UseMiddleware<CustomAuthenticationMiddleware>();
{ "pile_set_name": "StackExchange" }
Q: finding height and width of an image using numpy and pixel locations I've converted two images into numpy arrays image1Array image2Array Both images have been converted to grayscale, so there are only 0 or 255 values. In both examples, there are many rows of white at the top (and bottom): [255 255 255 255 .... 255 255 255 255] I believe what i'm referring to as 'row' is really an array. I'm new to using Numpy. So, there is an array for every line in the image, and every pixel in that line is represented with a 0 or 255. How do I find the first row that contains a black 0 pixel and the last row that contains a black 0 pixel? I should be able to use that to calculate the height. In these examples, this should be approximately the same number. I believe numpy.where(image1Array == 0)[0] is returning the row of every black pixel; min() and max() of that seems to be what i'm looking for, but i'm not sure yet. Conversely, how do I find the width of each image? In these examples, Image 2 should have a larger width number than Image 1 EDIT I think all I need is something like this: Height (the difference between the first row with a black pixel and the last row with a black pixel): (max(numpy.where(image1Array == 0)[0])) - (min(numpy.where(image1Array == 0)[0])) Width (the difference between the lowest column value with a black pixel and the highest column value with a black pixel): (max(numpy.where(image1Array == 0)[1])) - (min(numpy.where(image1Array == 0)[1])) So far, my testing is showing this is correct. Comparing the two images in the example above, their heights are equal while image2Array's width is double that of image1Array. A: You would want something like this: mask = x == 0 # or `x != 255` where x is your array columns_indices = np.where(np.any(mask, axis=0))[0] rows_indices = np.where(np.any(mask, axis=1))[0] first_column_index, last_column_index = columns_indices[0], columns_indices[-1] first_row_index, last_row_index = rows_indices[0], rows_indices[-1] Explanation: Let's create an example array using np.pad1 import numpy as np x = np.pad(array=np.zeros((3, 4)), pad_width=((1, 2), (3, 4)), mode='constant', constant_values=255) print(x) [[255. 255. 255. 255. 255. 255. 255. 255. 255. 255. 255.] [255. 255. 255. 0. 0. 0. 0. 255. 255. 255. 255.] [255. 255. 255. 0. 0. 0. 0. 255. 255. 255. 255.] [255. 255. 255. 0. 0. 0. 0. 255. 255. 255. 255.] [255. 255. 255. 255. 255. 255. 255. 255. 255. 255. 255.] [255. 255. 255. 255. 255. 255. 255. 255. 255. 255. 255.]] From here we can get a boolean mask array of zero elements as simple as that: mask = x == 0 print(mask) [[False False False False False False False False False False False] [False False False True True True True False False False False] [False False False True True True True False False False False] [False False False True True True True False False False False] [False False False False False False False False False False False] [False False False False False False False False False False False]] Now we could use np.any to get those rows where there is at least one zero-element. For columns: print(np.any(mask, axis=0)) >>> [False False False True True True True False False False False] and for rows: print(np.any(mask, axis=1)) >>> [False True True True False False] Now we only have to convert boolean arrays to arrays of indices2: columns_indices = np.where(np.any(mask, axis=0))[0] print(columns_indices) >>> [3 4 5 6] rows_indices = np.where(np.any(mask, axis=1))[0] print(rows_indices) >>> [1 2 3] Getting the first and the last rows/columns indices from here is pretty easy: first_column_index, last_column_index = columns_indices[0], columns_indices[-1] first_row_index, last_row_index = rows_indices[0], rows_indices[-1] Timings: I used the following code to calculate timings and plot them: Plot timings for a range of inputs. Comparing my version with your version but refactored as this: indices = np.where(x == 0) first_row_index, last_row_index = indices[0][0], indices[0][-1] first_column_index, last_column_index = indices[1][0], indices[1][-1] plot_times([georgy_solution, yodish_solution], np.arange(10, 200, 5), repeats=500) plot_times([georgy_solution, yodish_solution], np.arange(200, 10000, 800), repeats=1) 1 See How to pad numpy array with zeros for nice examples. 2 How to turn a boolean array into index array in numpy.
{ "pile_set_name": "StackExchange" }
Q: Is GoogleMock not thread safe on Linux? I started with testing GoogleMock (1.8.0 release) on Windows. I wanted to show an example that it is not thread safe. After proving that successfully, I wanted to show that the same test runs fine on Linux. That failed however. That did not match my expectation. Since the GoogleMock documentation says that it is, or should be, thread safe on systems with pthreads, it should be thread safe on Linux. I did have to add -pthread to the linker command line to build the executable. That means that GoogleMock or GoogleTest does use pthreads. This is the code I use for testing: #include <thread> #include <vector> #include "gmock/gmock.h" class Dummy { public: virtual void SomeMethod(int) {} }; class DummyMock : public Dummy { public: MOCK_METHOD1(SomeMethod, void(int)); }; using ::testing::Exactly; constexpr static int nrCallsPerThread = 100 * 1000; constexpr static int nrThreads = 10; TEST(SomeTest, Test100) { DummyMock dummy; std::vector<std::thread> threads; for (int i = 0; i < nrThreads; i++) { EXPECT_CALL(dummy, SomeMethod(i)).Times(Exactly(nrCallsPerThread)); threads.emplace_back([&dummy, i] { for (int j = 0; j < nrCallsPerThread; j++) { dummy.SomeMethod(i); } }); } for (auto& t: threads) { t.join(); } } int main(int argc, char** argv) { testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); } The problem is, on Linux, not exposed every execution. But running the executable with --gtest_repeat=100 has a near 100% hit rate. On Windows, using Visual Studio 2015, if get a Debug Assertion Failed! message with Expression: vector iterator not decrementable. On Linux, Ubuntu 17.04, when I run the Debug build from the command line I get [ FATAL ] ../googletest-release-1.8.0/googletest/include/gtest/internal/gtest-port.h:1928:: pthread_mutex_lock(&mutex_)failed with error 22. When running in a debugger on Linux, the program is (often) interrupted at gtest-port.h line 1100, which is line 2 in this callstack: 0 0x5555555a6633 testing::Cardinality::ConservativeUpperBound() const () (??:??) 1 0x5555555a1a13 testing::internal::ExpectationBase::CheckActionCountIfNotDone() const () (??:??) 2 0x555555563f98 testing::internal::TypedExpectation<void (int)>::ShouldHandleArguments(std::tuple<int> const&) const(this=0x5555557f58a0, args=std::tuple containing = {...}) (../googletest-release-1.8.0/googlemock/include/gmock/gmock-spec-builders.h:1100) 3 0x55555556397d testing::internal::FunctionMockerBase<void (int)>::FindMatchingExpectationLocked(std::tuple<int> const&) const(this=0x7fffffffde38, args=std::tuple containing = {...}) (../googletest-release-1.8.0/googlemock/include/gmock/gmock-spec-builders.h:1723) 4 0x555555563578 testing::internal::FunctionMockerBase<void (int)>::UntypedFindMatchingExpectation(void const*, void const**, bool*, std::ostream*, std::ostream*)(this=0x7fffffffde38, untyped_args=0x7fffde7fbe14, untyped_action=0x7fffde7fb7d0, is_excessive=0x7fffde7fb7c7, what=0x7fffde7fb900, why=0x7fffde7fba90) (../googletest-release-1.8.0/googlemock/include/gmock/gmock-spec-builders.h:1687) 5 0x5555555a265e testing::internal::UntypedFunctionMockerBase::UntypedInvokeWith(void const*) () (??:??) 6 0x55555555fcba testing::internal::FunctionMockerBase<void (int)>::InvokeWith(std::tuple<int> const&)(this=0x7fffffffde38, args=std::tuple containing = {...}) (../googletest-release-1.8.0/googlemock/include/gmock/gmock-spec-builders.h:1585) 7 0x55555555f16c testing::internal::FunctionMocker<void (int)>::Invoke(int)(this=0x7fffffffde38, a1=1) (../googletest-release-1.8.0/googlemock/include/gmock/gmock-generated-function-mockers.h:101) 8 0x55555555ecb6 DummyMock::SomeMethod(this=0x7fffffffde30, gmock_a1=1) (/home/jos/Programming/ThreadSafeGMock/main.cpp:16) 9 0x55555555d31e SomeTest_Test100_Test::<lambda()>::operator()(void) const(__closure=0x5555557f5478) (/home/jos/Programming/ThreadSafeGMock/main.cpp:36) 10 0x55555555de98 std::_Bind_simple<SomeTest_Test100_Test::TestBody()::<lambda()>()>::_M_invoke<>(std::_Index_tuple<>)(this=0x5555557f5478) (/usr/include/c++/6/functional:1391) 11 0x55555555de22 std::_Bind_simple<SomeTest_Test100_Test::TestBody()::<lambda()>()>::operator()(void)(this=0x5555557f5478) (/usr/include/c++/6/functional:1380) 12 0x55555555ddf2 std::thread::_State_impl<std::_Bind_simple<SomeTest_Test100_Test::TestBody()::<lambda()>()> >::_M_run(void)(this=0x5555557f5470) (/usr/include/c++/6/thread:197) 13 0x7ffff7b0a83f ??() (/usr/lib/x86_64-linux-gnu/libstdc++.so.6:??) 14 0x7ffff76216da start_thread(arg=0x7fffde7fc700) (pthread_create.c:456) 15 0x7ffff735b17f clone() (../sysdeps/unix/sysv/linux/x86_64/clone.S:105) Since it should be thread safe, I suspect that I am doing something wrong. But I do not see what. Or did I hit a bug in GoogleTest or GoogleMock? A: From the fine manual: Important note: Google Mock requires expectations to be set before the mock functions are called, otherwise the behavior is undefined. In particular, you mustn't interleave EXPECT_CALL()s and calls to the mock functions. Your original code fails on my system (cygwin) intermittently with error 22 or sometimes no message/error code whatsoever. This modification works flawlessly: for (int i = 0; i < nrThreads; i++) { EXPECT_CALL(dummy, SomeMethod(i)).Times(Exactly(nrCallsPerThread)); } std::vector<std::thread> threads; for (int i = 0; i < nrThreads; i++) { threads.emplace_back([&dummy, i] ...
{ "pile_set_name": "StackExchange" }
Q: Is the map $\omega\mapsto (X(\omega),Y(\omega))$ measurable with respect to $\sigma(X,Y)$? Definitions: We have a measure space $(\Omega,\sigma(X,Y),\mu)$ where $X,Y$ are maps from $\Omega$ to some measure space $(S,\Sigma,m)$. Here $\sigma(X,Y)$ is the smallest sigma algebra that makes both $X,Y$ measurable. Now is it true that the map $g:\Omega \to (S^2,\Sigma^2,m\times m)$ given by $\omega\mapsto (X(\omega),Y(\omega))$ is measurable? (Here $S^2$ is endowed with typical product measure/sigma algebra). So I have to show that for any $A\in \Sigma\times\Sigma$, $g^{-1}(A) \in \sigma(X,Y)$ but I just don't see how I could express $g^{-1}(A)$ in terms of $\sigma(X,Y)$ measurable sets. I feel like I'm missing something obvious. A: The product $\sigma$-algebra is generated by sets of the form $B\times C$ for $B,C\in\Sigma$. So it suffices to show that $g^{-1}(B\times C)\in \sigma(X,Y)$ for any $B,C\in\Sigma$ (the set of $A$ such that $g^{-1}(A)\in \sigma(X,Y)$ is a $\sigma$-algebra, so if it contains all sets of the form $B\times C$, it contains the entire product $\sigma$-algebra). You should be able to finish from here by thinking about what it means for $\omega\in\Omega$ to be an element of $g^{-1}(B\times C)$.
{ "pile_set_name": "StackExchange" }
Q: using gsub to remove strings but not numeric I have a dataframe that looks like this id col1 1 4 2 - 3 + 4 _ 5 N 6 text-abc 7 50 I am aiming to have a dataframe that looks like this: id col1 1 4 2 0 3 0 4 0 5 0 6 0 7 50 I want to keep the numeric values the way they are and convert the "-", "+", "_", "N", and "text-abc" into zeros. That is, I'd only like numeric values to be in this column, convert texts and other strings into zeros and leave the numeric values as they are. This is a very long column (ie thousands of rows) and may contain other unneccessary text. To fix, I tried to do it manually by using the following: df$col1 <- gsub("text-abc", 0, df$col1) df$col1 <- gsub("+", 0, df$col1) df$col1 <- gsub("-", 0, df$col1) df$col1 <- gsub("_", 0, df$col1) df$col1 <- gsub("N", 0, df$col1) However, as mentioned, this is not practical for large sets of data. As such, I tried the following: df$col1 <- gsub("[^[[:alnum:]]", 0, df$col1) But it simply changed "text-abc" to "text0abc" instead of turning the whole thing into 0. Ideally, I'd like the column to only contain numeric values. Any help would be greatly appreciated. Thank you so much in advance for your time! A: Instead of converting column on case by case basis, we can use as.numeric to change non-numeric column to NAs and then convert those NA's to 0. df$col1 <- as.numeric(df$col1) #Use this if `col1` is factor #df$col1 <- as.numeric(as.character(df$col1)) df$col1[is.na(df$col1)] <- 0 df # id col1 #1 1 4 #2 2 0 #3 3 0 #4 4 0 #5 5 0 #6 6 0 #7 7 50
{ "pile_set_name": "StackExchange" }
Q: input code needs a slight modification With this code, specified cells are copied into a database worksheet and then clears the data form for the next entry. How can I modify the code so that one (or perhaps more than one) cell is not cleared? Option Explicit Sub UpdateLogWorksheet() Dim historyWks As Worksheet Dim inputWks As Worksheet Dim nextRow As Long Dim oCol As Long Dim myRng As Range Dim myCopy As String Dim myCell As Range ActiveSheet.Unprotect "sallygary" 'cells to copy from Input sheet - some contain formulas myCopy = "g12,g14,g18,g20,g22,g24,i16,i18,i20,i22,i24,k16,k18,k20,k22,k24,m16,m18,m20,m22,m24,o16,o18,o20,o22,o24,q16,q18,q20,q22,q24,s16,s18,s20,s22,s24,u16,u18,u20,u22,u24" Set inputWks = Worksheets("Input") Set historyWks = Worksheets("1_Data") With historyWks nextRow = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Row End With With inputWks Set myRng = .Range(myCopy) 'If Application.CountA(myRng) <> myRng.Cells.Count Then ' MsgBox "Please fill in all the cells!" ' Exit Sub 'End If End With With historyWks With .Cells(nextRow, "A") .Value = "e4" .NumberFormat = "mm/dd/yyyy" 'hh:mm:ss End With .Cells(nextRow, "B").Value = Application.UserName oCol = 3 For Each myCell In myRng.Cells historyWks.Cells(nextRow, oCol).Value = myCell.Value oCol = oCol + 1 Next myCell End With 'clear input cells that contain constants With inputWks On Error Resume Next With .Range(myCopy).Cells.SpecialCells(xlCellTypeConstants) .ClearContents Application.GoTo .Cells(1) ', Scroll:=True End With On Error GoTo 0 End With ActiveSheet.Protect "sallygary" Range("g12").Select End Sub A: Add another string variable similar to the myCopy var. dim myCopy as string, myClear as string 'cells to copy from Input sheet - some contain formulas myCopy = "g12,g14,g18,g20,g22,g24,i16,i18,i20,i22,i24,k16,k18,k20,k22,k24,m16,m18,m20,m22,m24,o16,o18,o20,o22,o24,q16,q18,q20,q22,q24,s16,s18,s20,s22,s24,u16,u18,u20,u22,u24" 'cells to CLEAR from Input sheet myClear = "g12,g18,g22,i16,i20,i24,k18,k22,m16,m20,m24,o18,o22,q16,q20,q24,s18,s22,u16,u20,u24" Now use that range definition to clear the cell contents. With .Range(myClear).Cells.SpecialCells(xlCellTypeConstants) .ClearContents Application.GoTo .Cells(1) ', Scroll:=True End With
{ "pile_set_name": "StackExchange" }
Q: Real and imaginary part of holomorphic function assume maxima and minima on boundary How can I show: Let $Ω$ be a domain and assume that $f ∈ C(\bar \Omega)$ restricts to a holomorphic function on $Ω$. Prove: The real and imaginary part of $f$ assume their maxima and minima on the boundary of $Ω$. Maybe I could show that the real and imaginary part are again holomorphic and then I apply the maximum principle on the real and imaginary part?! Is it actually true that those functions are holomorphic? Any hints would be great! A: Decompose $f(z)$ into its real and imaginary parts: $$f(z) = f(x,y) \equiv u(x,y) + iv(x,y)$$ Apply the Cauchy-Riemann conditions: $$ \frac{\partial u}{\partial x} = \frac{\partial v}{\partial y} \\\frac{\partial u}{\partial y} = -\frac{\partial v}{\partial x}$$ From these, it easily follows that: $$\nabla^2u=0\\\nabla^2v=0$$ This implies that both $u$ and $v$ are solutions to Laplace's equation, which implies that they have no local maxima or minima (their maxima/minima must lie on the boundary of the region).
{ "pile_set_name": "StackExchange" }
Q: Scala implicit object vs implicit val I've seen two ways (one less than the other) of declaring implicit for typeclass pattern in Scala. implicit val instance1 = new Typeclass { def do = ??? } implicit object instance2 extends Typeclass { def do = ??? } How are they different? Should one prefer one to the other for certain times? I find implicit val much more commonly used than implicit object and I've yet to find many resources about implicit object. A: One difference is that the object version is going to be lazily initialized, i.e. it's constructor will not be called until the first time it is used. For example: trait Incrementer[T] { def inc(x: T) } def increment[T](x: T)(implicit ev: Incrementer[T]) = ev.inc(x) implicit object IntIncrementer extends Incrementer[Int] { println("IntIncrementer is being constructed...") def inc(x: Int) = x + 1 } implicit val DoubleIncrementer extends Incrementer[Double] { println("DoubleIncrementer is being constructed...") def inc(x: Double) = x + 1D } Note that you will not see the message from IntIncrementer until it is used, e.g. increment(1) //this prints "IntIncrementer is being constructed..." The message from DoubleIncrementer, however, will be displayed when it is defined. So the initialization of implicit object is lazy while the initialization of implicit val is strict.
{ "pile_set_name": "StackExchange" }
Q: How to set dynamic data-title in ngtable (angular plugin) I want have a multi language view with an ngTable. For do that, i set in my controller a $scope.translate (a valid json) who contains my traductions. In my view i want set my data-title like {{translate.code}} etc... my view : <table ng-table="tableParams" class="table ng-table-responsive"> <tr ng-repeat="product in $data"> <td data-title="'{{translate.code}}'" > <!-- display : {{translate.code}} --> {{product.code}} </td> <td data-title="['translate.reference']" > <!-- display : empty --> {{product.reference}} </td> <td data-title="'Label'" > {{product.label}} </td> <td data-title="'Size'" ng-show="manageSizeColor == true"> {{product.size}} </td> <td data-title="'Quantity'" > <ac-quantity minquantity="1" cquantity="product.quantity"></ac-quantity> </td> <td data-title="'Price'"> <b>{{product.price + currency}}</b> </td> </tr> </table> A: If you're using angularjs ~1.2 with angular-translate ~2.6.1, translation on data-title works like this: <td data-title="'MY_TRANSLATION_ID' | translate" > {{product.reference}} </td> A: I' ve finally found how do this, with this example : https://github.com/esvit/ng-table/issues/53 <td data-title="translate['reference']" > {{product.reference}} </td> where translate is the scope variable and ['reference'] is the property
{ "pile_set_name": "StackExchange" }
Q: Setting up a fund screening strategy I wonder if some of you guys have been applying some kind of analysis/screening when you choose which funds (hedge funds or other funds) you are going to invest your money in? If you are, so what criterios do you use, or do you even have some example code? I am thinking about to use quantmod library and PerformanceAnalytics library. And of course some other libraries too... Greatful for any comments/guidelines! Best Regards! A: I think the function you are looking for is sample. For example, if funds is a list of fund names: > funds<-LETTERS[1:10] > funds [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" Then sample(funds) will give you a pretty good strategy to choose which funds to invest in: > sample(funds,5) [1] "G" "A" "F" "C" "J" If you want to get more sophisticated, then you could allocate a portion of your money to each fund. In this case, the function runif is probably a good one. Something like this: > data.frame(fund=funds,allocation={x<-runif(10);x/sum(x)}) fund allocation 1 A 0.139513790 2 B 0.156152098 3 C 0.048013319 4 D 0.163331697 5 E 0.123784522 6 F 0.116643687 7 G 0.008980385 8 H 0.067164346 9 I 0.081205814 10 J 0.095210342 Disclaimer: taking investment advice from the internet is not usually a good idea!
{ "pile_set_name": "StackExchange" }
Q: Stop user from using enter to pass a form Due to an issue relating to a horrible mobile device (that work has given me no choice but to work with) I have to stop the use of the enter key from registering in form in HTML. The only way I'd like the data to be submitted is when the submit button is pressed. Hope this is enough to help work out my problem! If not feel free to ask more. A: See here for an example.
{ "pile_set_name": "StackExchange" }
Q: Simple GUI calculator application java I'm newbie and am having a problem. I created a gui with netbeans design view that contains 30 JTextFields. Then arrainged these textfields into 3 columns of 10 textfields each. So the idea is to have the user to be able to enter numbers into 2 of the columns of textfields then multiply corresponding rows of the first 2 columns and the result to be shown in the third column of textfields. So far I have float a1 = Float.parseFloat(text1.getText()) //This 30 times one for each field float [] cola; cola = newfloat[10] //I did this 3 times to create 3 columns cola[0] = a1 // I did this to place the variables in the columns cola[1] = a2 // cola and colb for retrieved from user and colc for results and this continues creating 3 columns... Then I multiply them together like so... result = (colla*colb); colc.setText(String.valueOf(result)); BUT this doesn't work. My desired result is to have the 10 textfields I arrainged into 'colc' to be the product of user input from the 2 columns of textfields. I think I am approaching this problem all wrong or maybe just a line of code is missing? Any help would be much appreciated! A: And for your problem you mentioned in the comments (which I will repeat here for clarity as code in comments isn't very pleasing to the eye): public static void main(String[] args) { int arr[] = {9,9,9}; int arr1[] = {9,9,9}; int sum[] = {0,0,0}; for (int i=0; i < arr.length; i++) sum = arr[i] + arr1[i]; System.out.println(sum); } This has one compile error in it, and one thing you probably do not want either. the sum = arr[i] + arr1[i]; will not compile. If you take some time to think about this ... on the left hand side you have an array (an int array of length 3), and you try to assign a single int to this on the right hand side. What you probably want to do is sum[i]=arr[i] + arr1[i];, The System.out.println(sum); will print out gibberish as an array has a poorly implemented toString. What you probably want to use is the Arrays#toString method This are rather basic array operations, so you might want to read an Java array tutorial again.
{ "pile_set_name": "StackExchange" }
Q: Saving Alamofire request data into a variable I'm having troubles with getting password salt from my VM server via Alamofire. I'm making a request to server and it should return me salt, so I can salt my password, hash it and send it back to server. The problem is that I do not understand how to save the salt, that Alamofire receives, into a variable, so I can just add it to password and hash it like that: let salted_password = user_password + salt let hash = salted_password.sha1() Where user_password is what the user entered into password field and salt is what I got from Alamofire salt request. Here is my code: func getSalt(completionHandler: @escaping (DataResponse<String>, Error?) -> Void) { Alamofire.request("http://192.168.0.201/salt", method: .post, parameters: salt_parameters).responseString { response in switch response.result { case .success(let value): completionHandler(response as DataResponse<String>, nil) case .failure(let error): completionHandler("Failure", error) } } } let salt = getSalt { response, responseError in return response.result.value! } It gives me the following error: Binary operator '+' cannot be applied to operands of type 'String' and '()'. So is it possible to save a request value into a variable? What should I do? Thank you for your attention. A: The problem here is because of how you implemented your completion block For example: func someAsynchronousCall(a: Int, b: Int, @escaping block: (_ result: Int) -> Void) { ... some code here ... { // let's just say some async call was done and this code is called after the call was done block(a + b) } } To use this code it would look like this: var answer: Int = 0 someAsynchronousCall(100, b: 200) { result in // the `result` is like what you're returning to the user since API calls need to be called asynchronously you do it like this rather than creating a function that has a default return type. answer = result print(answer) } print(answer) The print would look like this 0 300 Since we declared answer as 0 it printed that first since the async call wasn't done yet, after the async call was done (usually a few milliseconds after) it then printed 300 So all in all your code should look something like this var salt: String? getSalt { response, responseError in salt = response.result.value }
{ "pile_set_name": "StackExchange" }
Q: Does cassette tape change its velocity while playing? Looking at the old cassette tape, From the POV of the head, let's say that it reads at speed \$v\$ (the magnetic medium scrolls at speed \$v\$). But looking at the right wheel, which is the one that's pooling the magnetic medium - its radius is growing(!) over time. Now, \$v=r\omega\$, where \$\omega\$ is the angular velocity, i.e. a constant Question I don't think that's true. What is really going on here? Radius is growing over time, for sure. I also assume that \$\omega\$ is constant. so did \$v\$ increase? A: The details of how a cassette drive works are well covered by this Wikipedia article. The tape is pulled by a capstan next to the playback head, and this capstan pulls the tape at a steady rate. (picture from the Wikipedia article) You probably need to click on the picture to see it full size. I have indicated the capstan by a red arrow. The take-up spool doesn't rotate at a fixed speed. It uses a slipping drive, as badjohn says in his answer, so it takes up the tape at the speed the capstan moves it. A: The specific mechanisms for cassette players and decks largely depended on how much you paid for them. On inexpensive players, the capstan, feed reel and take up reel would be driven by the same motor, connected by belts. On the best decks, the capstan and the reals would each have a separate motor. Mid priced decks could have two motors, one for the capstan and one for the reels. On a one or two motor system there would be a slip mechanism driving the take up and feed reels. The feed reel need to put reverse pressure on the tape to maintain tension across the heads. The clutch that allowed the reels to turn at variable speeds could be a simple as letting the belt slip on the pulley. I saw a number of these when disassembling broken players as a kid. On three motor systems, the reels would be driven in the appropriate direction by its own motor. Presumably it was a relatively low torque motor so it would not stretch the tape. Either way, the rotation of the capstan, pressing against the pinch roller would govern the speed of tape travel. The 1 7/8 inch per second speed was the standard, but some players could play at other speeds, usually to extend the recording time for low fidelity used, such as voice notes. During fast forward or rewind the pinch roller is pulled back from the capstan. On a one motor system, the capstan would spin at a faster rate. On a multi-motor system the capstan would be still. Auto-reverse decks added more mechanisms and had two capstans and pinch rollers. A: The speed past the head is constant: 1⅞ inches per second. A slipping clutch allows the take up reel to vary its speed as required.
{ "pile_set_name": "StackExchange" }
Q: Retrieve data from phpmyadmin I wrote this code to retrieve data from phpmyadmin. But when the i load the page "retrieve.php" in my browser then all the result show up without any search. Later when i do search by specific name then those field go and only the one that i searched for show. May i know how do i get rid of the display that i get when i am not doing any search ? Basically what i want to do is that when i load the page "retrieve.php" then no field from database should display until i search for any specific name. <?php echo "<body style='background-color:gray'>"; include ("account.php"); ( $dbh = mysql_connect( $hostname, $username, $password )) or die ( "uable to connect to MYSQL database" ); mysql_select_db( $project ); $sql= "SELECT * FROM registration "; $query=mysql_query($sql) or die(mysql_error()); if (isset($_POST['search'])) { $search_term = mysql_real_escape_string($_POST['search_box']); $sql .= "WHERE first_name= '{$search_term}'"; $sql .= " OR last_name= '{$search_term}'"; } $query=mysql_query($sql) or die(mysql_error()); ?> <html> <head> <title>jon</title> </head> <body> <form name="search_form" method="POST" action="retrieve.php"> <table width="599" border="1"> <tr> <th>Search <input type ="text" name ="search_box" value=""/> <input type="submit" name="search" value="Find Users"> </tr> </table> </form> <table width="600" border="1"> <tr> <th width="91"> <div align="center">First Name </div></th> <th width="98"> <div align="center">Last Name </div></th> <th width="198"> <div align="center">Email </div></th> <th width="97"> <div align="center">City </div></th> <th width="59"> <div align="center">Country </div></th> <tr> <?php while ($row=mysql_fetch_array($query)){ ?> <tr> <td><?php echo $row['first_name'];?></td> <td><?php echo $row['last_name'];?></td> <td><?php echo $row['email'];?></td> <td><?php echo $row['address_city'];?></td> <td><?php echo $row['address_country'];?></td> <tr> <?php } ?> </table> A: Try the following: <?php echo "<body style='background-color:gray'>"; include ("account.php"); ( $dbh = mysql_connect( $hostname, $username, $password )) or die ( "uable to connect to MYSQL database" ); mysql_select_db( $project ); if (isset($_POST['search'])) { $sql= "SELECT * FROM registration "; $search_term = mysql_real_escape_string($_POST['search_box']); $sql .= "WHERE first_name= '{$search_term}'"; $sql .= " OR last_name= '{$search_term}'"; $query=mysql_query($sql) or die(mysql_error()); } ?> <html> <head> <title>jon</title> </head> <body> <form name="search_form" method="POST" action="retrieve.php"> <table width="599" border="1"> <tr> <th>Search <input type ="text" name ="search_box" value=""/> <input type="submit" name="search" value="Find Users"> </tr> </table> </form> <table width="600" border="1"> <tr> <th width="91"> <div align="center">First Name </div></th> <th width="98"> <div align="center">Last Name </div></th> <th width="198"> <div align="center">Email </div></th> <th width="97"> <div align="center">City </div></th> <th width="59"> <div align="center">Country </div></th> <tr> <?php if (isset($_POST['search'])) { while ($row=mysql_fetch_array($query)){ ?> <tr> <td><?php echo $row['first_name'];?></td> <td><?php echo $row['last_name'];?></td> <td><?php echo $row['email'];?></td> <td><?php echo $row['address_city'];?></td> <td><?php echo $row['address_country'];?></td> <tr> <?php }} ?> </table> Only do the query if there is a post result. Make sure to swap to MySQLi_* when you have the time as MySQL_* is depreciated.
{ "pile_set_name": "StackExchange" }
Q: EU Employer demands birth certificate - Why? My brother is Irish, he starts a job as manager of a bar in France. He provided his Irish Passport for id, and the employer wants an original birth certificate. My understanding is birth certificate, without being notarised, are not recognised outside there country of issue. In addition, they are not official documents for id (since they lack a photo). However, my understanding is passports are officially recognised internationally as id. Two other brothers live in Germany and Spain, both residents of those countries, both obtained their residency without any need for birth certificates (just passports). Birth certificates can be used as part of identity theft so alarm bells ring for me. Is there any reason why an employer might demand a birth certificate? Is there any reason why an Irish passport would not suffice? A: This is weird. Within the EU, a passport is proof of identity, and it is also proof that you are allowed to take a job in the EU. There is nothing that a birth certificate would add to this. Either the bar manager is badly misinformed, or he doesn't want to give your brother a job, and will come up with something even more ridiculouse if he provides his birth certificate.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to attach a gesture recognizer to a button, so that the user swipes up after/during the button press? I read through a few similar questions here, but most of them are for much older versions of Swift. This tutorial shows how to create a gesture recognizer and works pretty well: https://www.ioscreator.com/tutorials/swipe-gesture-ios-tutorial-ios11 What I'd like to accomplish is to add functionality that would allow the user to swipe up or down after pressing a button, while still holding the button, and have my app react to the combination of the specific button being pressed and the upward or downward swipe gesture. Here's the specific design I'm trying to implement. Basically I'd like the user to press the "A" button and then swipe up or down to get the "#" or "b". Is this possible? The # & b could be image views or buttons (though if they're buttons, I don't want them to be pressable on their own). If this is a crazy design, I welcome suggestions for improvement. A: You want to use a UILongPressGestureRecognizer (probably in conjunction with image views). It has the advantage that first it recognizes a finger held down in one spot (the "A") and then it tracks the movement of that finger (panning up to the sharp or down to the flat). Where the finger is held down — i.e., is it in the "A" or not — will determine whether to recognize in the first place. Then if you do recognize, you watch where the finger goes and decide whether it has entered the sharp or the flat.
{ "pile_set_name": "StackExchange" }
Q: Problematic behavior of Linq Union? consider the following example: public IEnumerable<String> Test () { IEnumerable<String> lexicalStrings = new List<String> { "test", "t" }; IEnumerable<String> allLexicals = new List<String> { "test", "Test", "T", "t" }; IEnumerable<String> lexicals = new List<String> (); foreach (String s in lexicalStrings) lexicals = lexicals.Union (allLexicals.Where (lexical => lexical == s)); return lexicals; } I'd hoped for it to produce "test", "t" as output, but it does not (The output is only "t"). I'm not sure, but may have to do something with the deferred processing. Any ideas how to get this to work or for a good alternative? Edit: Please note that this is just a simplified example. lexicalStrings and allLexicals are different types in the original code. So I cannot directly combine these. Edit2 the problem to solve looks more like this: public IEnumerable<Lexical> Test () { IEnumerable<String> lexicalStrings = new List<String> { "test", "t" }; IEnumerable<Lexical> allLexicals = new List<Lexical> { ... }; IEnumerable<Lexical> lexicals = new List<Lexical> (); foreach (String s in lexicalStrings) lexicals = lexicals.Union (allLexicals.Where (lexical => lexical.Text == s)); return lexicals; } A: You are using wrong operation as other answer explaining. But still it is interesting why your code works incorrectly despite looking fine. let's modify your app a bit: IEnumerable<String> lexicalStrings = new List<String> { "test", "t" }; IEnumerable<String> allLexicals = new List<String> { "test", "Test", "T", "t" }; IEnumerable<String> lexicals = new List<String>(); foreach (String s in lexicalStrings) { lexicals = lexicals.Union( allLexicals.Where( lexical => { Console.WriteLine(s); return lexical == s; } ) ); } Console.WriteLine(); foreach (var item in lexicals) { } what output do you expect? here is it: t t t t t t t t interesting, is not it? now let's modify it again: IEnumerable<String> lexicalStrings = new List<String> { "test", "t" }; IEnumerable<String> allLexicals = new List<String> { "test", "Test", "T", "t" }; IEnumerable<String> lexicals = new List<String>(); foreach (String s in lexicalStrings) { string ls = s; lexicals = lexicals.Union( allLexicals.Where( lexical => { Console.WriteLine(ls); return lexical == ls; } ) ); } foreach (var item in lexicals) { } now the output and results are fine: test test test test t t t t Why does it happen? You use closure - the use of outer var in inner lambda. Since you do not actually iterate your sequence the current value of s doesn't get into the lambda. foreach exits and all inner copies of s hold value of last iteration. In case of inner variable they hold values copies that are created for every iteration. This conflict comes from inner lazyness of LINQ. If you do things like List.AddRange inside loop result will be fine, because List.AddRange forces iteration.
{ "pile_set_name": "StackExchange" }
Q: Flask WTForms - Is it possible to use step parameter for allowing setting seconds in TimeField? I've just discovered the existence of wtforms.fields.html5 with TimeField, DateField etc. inside. Normally in HTML one would write the following <input type="time" step="1"/> to render a field for setting time. Since I'm generating a form (with various <input/> fields incl. one for time) in Python I'm struggling to find a way to set the step parameter. I tried adding an extra argument to the constructor called step just to check if it exists. Didn't work, doesn't exist. In addition I tried setting the format: task_clock_due = TimeField('Time due', validators=[validators.InputRequired()], format='%H:%M:%S' ) Since the format includes hours, minutes and seconds I was actually expecting the time field to get the seconds part too. Apparently it doesn't work like this. I would still get the seconds, whenever I submit the value but it's always 00 and the user has no way of actually interacting with the seconds. I went as deep as checking the source code of the specific widget but nothing came out. A: I got it. Apparently there is the render_kw argument, which can also be used - for example - in a TextField to set the placeholder to a specific value. The solution: task_clock_due = TimeField('Time due', validators=[validators.InputRequired()], format='%H:%M:%S', render_kw={"step": "1"} )
{ "pile_set_name": "StackExchange" }
Q: DB_PREFIX and security against SQL injections and other attacks Maybe a stupid question but just curious. Couldn't find anything on search. So I know DB_PREFIX is used to differentiate between different tables in a db, which might come from a different "source" as pointed out here. Im using DB_PREFIX which is declared as a constant in config.php As I continue my learning journey with PHP this is the first time I'm working with DB_PREFIX (modifying someone elses script) So I was just curious, consider the following simple statement. $sql = "SELECT gameID from ". DB_PREFIX . "schedule WHERE weekNum = :weekNum AND homeID = :homeID"; $stmnt = $db->prepare($sql); $stmnt->bindValue(':weekNum', $week); $stmnt->bindValue(':homeID', $teamName ); $stmnt->execute(); if ($stmnt->rowCount() > 0) { $IDs = $stmnt->fetchAll(); foreach ($IDs as $ID){ $gameID = $ID['gameID']; } //echo $gameID; return $gameID; } else { die('Error getting game id: '); } config.php define('DB_PREFIX', 'bru_'); Does DB_PREFIX provide some "extra" layer of security? Is it good practice using DB_PREFIX? A: Having a custom prefix in all application tables can serve two purposes: Sharing the same database with other apps. That's something that only makes sense with really cheap hosting services—and in 2017 that means a really low-cost service. Having a multi-tenant application (a single app that splits its data across several copies of the same table set). These kind of apps tend to be a maintenance nightmare. It can't possibly add any extra security because it doesn't attempt to. It isn't a security feature at all. In fact, for the security standpoint it could be argued that it can actually increase risks. If you are sharing storage with some other arbitrary application it's very likely that you're also sharing the same MySQL user with the same read and write privileges on the complete database. In such case, the other app can easily wipe out your tables, either intentionally or by mistake. About the good practice part... That's always fairly subjective. My personal opinion is that it provides a dubious benefit (sharing a database is like sharing bath water, it only makes sense if you live in a desert) and it makes writing SQL code more annoying. For instance, you can no longer copy and paste between your PHP code and your MySQL client and, if you use an IDE that recognises SQL inside PHP strings, you'll no longer get proper code intelligence.
{ "pile_set_name": "StackExchange" }
Q: Implementation of a Sudoku Solver I know it may be fairly bad. I want to find out exactly how horrendous it is and any suggestions on how to improve are appreciated. public class SudokuSolver_4{ //Creating the main sudoku board int sudokuGraph[][] = new int[9][9]; public boolean attemptAssignValue(int leftIndex, int upIndex){ //Attempt to assign a value to the specified cell for(int x = 0; x < 10 ; x++){ if(notContainedInRow(leftIndex, x) && notContainedInColumn(upIndex, x) && notContainedInSubGrid(leftIndex, upIndex, x)){ sudokuGraph[leftIndex][upIndex] = x; return true; } } return false; } public boolean attemptAssignValue(int leftIndex, int upIndex, int startValue){ //When the program backtracks and has to reassign a value, this overloaded version of the assignent function takes a third parameter - the value that the cell currently has, so that the program does not reassign it if(startValue != 9){ for(int x = startValue; x < 10; x++){ if(notContainedInRow(leftIndex, x) && notContainedInColumn(upIndex, x) && notContainedInSubGrid(leftIndex, upIndex, x)){ sudokuGraph[leftIndex][upIndex] = x; return true; } } return false; } else{ //This return is because it complained of no definite return statement in the method, as the other one was still in the larger if statement return false; } } public boolean notContainedInRow(int leftIndex, int numberToCheck){ //Uses a simple nested loop to check if the particular number is anywhere in the row for (int upIndex = 0; upIndex < 9; upIndex++){ if (sudokuGraph[leftIndex][upIndex] == numberToCheck){ return false; } } return true; } public boolean notContainedInColumn(int upIndex, int numberToCheck){ //Uses another nested loop to make sure that number is not anywhere in the column for (int leftIndex = 0; leftIndex < 9; leftIndex++){ if(sudokuGraph[leftIndex][upIndex] == numberToCheck){ return false; } } return true; } public boolean notContainedInSubGrid(int leftIndex, int upIndex, int numberToCheck){ /* A peice of code that could definitely be improved. It is a successive if else ladder that check which grid a particular value is in. The logic is simple: It assumes that each grid is bound by two indexes - one on the upper side and one on the left side. So if the cell was in the first grid, it's leftIndex would be less than three and its upIndex would also be less than three. And so on. And as the ladder is if else, we don't need to define a greater than condition.*/ int boundLeftIndex = 0; int boundUpIndex = 0; if (leftIndex < 3 && upIndex < 3){ boundLeftIndex = 0; boundUpIndex = 0; } else if (leftIndex < 3 && upIndex < 6){ boundLeftIndex = 0; boundUpIndex = 3; } else if (leftIndex < 3 && upIndex < 9){ boundLeftIndex = 0; boundUpIndex = 6; } else if (leftIndex < 6 && upIndex < 3){ boundLeftIndex = 3; boundUpIndex = 0; } else if (leftIndex < 6 && upIndex < 6){ boundLeftIndex = 3; boundUpIndex = 3; } else if (leftIndex < 6 && upIndex < 9){ boundLeftIndex = 3; boundUpIndex = 6; } else if (leftIndex < 9 && upIndex < 3){ boundLeftIndex = 6; boundUpIndex = 0; } else if (leftIndex < 9 && upIndex < 6){ boundLeftIndex = 6; boundUpIndex = 3; } else if (leftIndex < 9 && upIndex < 9){ boundLeftIndex = 6; boundUpIndex = 6; } //Returns the boolean result of a call to another method which actually check whether or not the value is in the grid return notContainedInGridCheck(boundLeftIndex, boundUpIndex, numberToCheck); } public boolean notContainedInGridCheck(int leftIndex, int upIndex, int numberToCheck){ //Uses a nested loop to traverse the subgrid and determine whether the value is present int x = leftIndex; int y = upIndex; for (x = leftIndex; x < leftIndex + 3; x++){ for (y = upIndex; y < upIndex + 3; y++){ if (sudokuGraph[x][y] == numberToCheck){ return false; } } } return true; } public int[] goBackOneCell(int leftIndex, int upIndex){ /* Simply returns the index values for the previous cell on the graph. If it works properly there should be no need to specify a exception for the beginning and end of the grid as the program shold never encounter that situation */ if (upIndex == 0){ upIndex = 8; leftIndex--; } else{ upIndex--; } int newValues[] = new int[2]; newValues[0] = leftIndex; newValues[1] = upIndex; return newValues; } public int[] goAheadOneCell(int leftIndex, int upIndex){ //Similar to the goBack function, this function returns the value of the next cell instead if (upIndex == 8){ upIndex = 0; leftIndex++; } else{ upIndex++; } int newValues[] = new int[2]; newValues[0] = leftIndex; newValues[1] = upIndex; return newValues; } public void showTable(){ //Used to print the graph for (int leftIndex = 0; leftIndex < 9; leftIndex++){ for (int upIndex = 0; upIndex < 9; upIndex++){ System.out.print(sudokuGraph[leftIndex][upIndex]); System.out.print(" "); } System.out.println(); System.out.println("------------------------------------"); } System.out.println(); System.out.println("**END**"); System.out.println(); } public void control(){ //The method which incorporates the above methods into a working solution int leftIndex = 0; int upIndex = 0; boolean assignmentAttempt; int values[] = new int[2]; //The first assignment must be done outside of the loop as the boolean assigmentAttempt must be true for the loop to run //Yes, there are a hundred other ways of doing this (probably) assignmentAttempt = attemptAssignValue(leftIndex, upIndex); //Infinite loop, that is acually a non-infinite loop with a specific exit criteria (like most forever loops I presume) for(; ;){ //The if statement that handles what to do after a successful assignment if(assignmentAttempt == true){ //Checks if the end of the graph has been reached, if so, it breaks if(leftIndex == 8 && upIndex == 8){ showTable(); break; } //If the end has not been reached, it goes ahead one cell and attempts the assignment again. The outcome of the assignment is expressed by the assignmentAttempt variable values = goAheadOneCell(leftIndex, upIndex); leftIndex = values[0]; upIndex = values[1]; //The next to print statements were only for debugging, they serve no useful purpose to the end user System.out.print(leftIndex); System.out.print(upIndex); System.out.println(); assignmentAttempt = attemptAssignValue(leftIndex, upIndex); } //The loop continues. If the assignment succeeded it goes back to the beginning after printing the table //Otherwise, it goes back one cell and attempts to assign again. Note that here, the overloaded version of the assignment method is used so that already previously assigned values are not reassigned //This if loop will continue to execute until another successful assignment occurs, ending the backtrack if(assignmentAttempt == false){ sudokuGraph[leftIndex][upIndex] = 0; values = goBackOneCell(leftIndex, upIndex); leftIndex = values[0]; upIndex = values[1]; //Again, the next two print statements are only for debugging System.out.print(leftIndex); System.out.print(upIndex); System.out.println(); //The same assignment variable is used for control assignmentAttempt = attemptAssignValue(leftIndex, upIndex, sudokuGraph[leftIndex][upIndex]); } //Printing the table at the end of each attempt showTable(); } } } A: Lifecycle What is the intended lifecycle of an object of this class? I don't see any constructor, and the field //Creating the main sudoku board int sudokuGraph[][] = new int[9][9]; is package-private. Is there some helper class which constructs an instance, fills in that array, and then calls control()? In my opinion it would be better to have a public constructor which takes the starting grid, and probably to only expose one other public method (something like public int[][] solve(). Representation //Creating the main sudoku board int sudokuGraph[][] = new int[9][9]; What I really want from that comment is an explanation of what the integers mean. Are they raw values from 1 to 9 with a sentinel indicating "not yet deduced"? Are they bitsets for possible values, ranging from 1 to 511? Naming public boolean attemptAssignValue(int leftIndex, int upIndex){ //Attempt to assign a value to the specified cell for(int x = 0; x < 10 ; x++){ if(notContainedInRow(leftIndex, x) && notContainedInColumn(upIndex, x) && notContainedInSubGrid(leftIndex, upIndex, x)){ I can work out what leftIndex and upIndex mean, but I think row and column would be clearer, especially since the method names do call them row and column. Sort-of. Actually, I would have guessed that leftIndex meant column and upIndex meant row, not the other way round. public boolean notContainedInRow(int leftIndex, int numberToCheck){ and similar: it's generally clearer to have method names without not, because if you need to test whether the number is in the row you end up with !notContainedInRow, and the double-negative requires more thought. I would change it to containedInRow and invert the return values. Subgrids public boolean notContainedInSubGrid(int leftIndex, int upIndex, int numberToCheck){ /* A peice of code that could definitely be improved. It is a successive if else ladder that check which grid a particular value is in. The logic is simple: It assumes that each grid is bound by two indexes - one on the upper side and one on the left side. So if the cell was in the first grid, it's leftIndex would be less than three and its upIndex would also be less than three. And so on. And as the ladder is if else, we don't need to define a greater than condition.*/ int boundLeftIndex = 0; int boundUpIndex = 0; if (leftIndex < 3 && upIndex < 3){ boundLeftIndex = 0; boundUpIndex = 0; } else if (leftIndex < 3 && upIndex < 6){ boundLeftIndex = 0; boundUpIndex = 3; } ... In order, here are three better ways to do this: Split left and up. boundLeftIndex depends solely on leftIndex, so you could have two sets of three ifs each rather than one set of nine. Use switch. switch (leftIndex) { case 0: case 1: case 2: boundLeftIndex = 0; break; case 3: case 4: case 5: boundLeftIndex = 1; break; case 6: case 7: case 8: boundLeftIndex = 2; break; default: throw new RuntimeException("Shouldn't be reachable"); } Use %. This gives the remainder after division. boundLeftIndex = leftIndex - (leftIndex % 3); boundUpIndex = upIndex - (upIndex % 3); Don't compare Booleans if(assignmentAttempt == true){ could be just if(assignmentAttempt){ and that's more widely accepted style except in languages like C which don't have a proper Boolean type. Similarly if(assignmentAttempt == false){ should be if(!assignmentAttempt){ Tidy your code //The next to print statements were only for debugging, they serve no useful purpose to the end user System.out.print(leftIndex); System.out.print(upIndex); System.out.println(); So remove them before posting it for review. KISS for(; ;){ //The if statement that handles what to do after a successful assignment if(assignmentAttempt == true){ ... assignmentAttempt = attemptAssignValue(leftIndex, upIndex); } //The loop continues. If the assignment succeeded it goes back to the beginning after printing the table //Otherwise, it goes back one cell and attempts to assign again. Note that here, the overloaded version of the assignment method is used so that already previously assigned values are not reassigned //This if loop will continue to execute until another successful assignment occurs, ending the backtrack if(assignmentAttempt == false){ ... assignmentAttempt = attemptAssignValue(leftIndex, upIndex, sudokuGraph[leftIndex][upIndex]); } //Printing the table at the end of each attempt showTable(); } This is quite complex to reason about. It would be much simpler to reason about for(; ;){ //The if statement that handles what to do after a successful assignment if(assignmentAttempt == true){ ... assignmentAttempt = attemptAssignValue(leftIndex, upIndex); } //The loop continues. If the assignment succeeded it goes back to the beginning after printing the table //Otherwise, it goes back one cell and attempts to assign again. Note that here, the overloaded version of the assignment method is used so that already previously assigned values are not reassigned //This if loop will continue to execute until another successful assignment occurs, ending the backtrack else{ ... assignmentAttempt = attemptAssignValue(leftIndex, upIndex, sudokuGraph[leftIndex][upIndex]); } //Printing the table at the end of each attempt showTable(); } Algorithm Backtracking is usually the last resort of a Sudoku solver. You would be able to get a significant speed-up with some very simple rules: the only cell in a row/column/subgrid which isn't blocked from having a number can be filled with that number; a cell which is blocked from having eight numbers can be filled with the remaining one. That solves most "easy" Sudokus without any backtracking. When backtracking is necessary, it's worth looking at heuristic approaches to pick the cell to guess rather than just taking the first one.
{ "pile_set_name": "StackExchange" }
Q: Why does deriveFont(float size) not change font size in a JButton? The deriveFont(float size) method just makes the Font plain without changing its size. JButton prevButton = new JButton("Previous"); prevButton.setFont(prevButton.getFont().deriveFont(90)); If I use deriveFont(int style, float size) like in the following example it works as intended. JButton prevButton = new JButton("Previous"); prevButton.setFont(prevButton.getFont().deriveFont(Font.BOLD, 90)); Can someone explain this behaviour? A: Check the variable arguments of all deriveFont overloads. When you deriveFont(90), (someone could say it is kind ambiguous) you are changing the style of the font and not the size. The method is deriveFont(int style), where accepted style values are Font.BOLD,Font.ITALIC and Font.PLAIN. In the other hand, another overload of this method is deriveFont(float size). Note the float. In order to make this work you should deriveFont((float) 90) or deriveFont(90f) as @camickr pointed in comments. Casting the int to float will make it clear you want to change the size.
{ "pile_set_name": "StackExchange" }
Q: What is the difference between these two sentences What is the difference between the sentence "He was tired because he was exercising too hard" and "He was tired because he had been exercising too hard"? A: The first one implies he was still exercising at the time he was tired. The second implies he was tired after exercising. It's a subtle difference but it's there. Grammatically it's the difference between past tense vs past participle, but you probably don't need to know that.
{ "pile_set_name": "StackExchange" }
Q: Angular using import from assets folder I have a library installed via npm and one of the modules I have modified. python.js So, just because if I delete the node_modules folder and run npm install I would lose the changes I need to put this module elsewhere? I currently import it like this: import 'brace/mode/phython'; So if I move my modified version of phython.js into the assets folder... How do I import it? A: Try something like this to see if it work import 'assets/brace/mode/phython';
{ "pile_set_name": "StackExchange" }
Q: Converting array of Objects to array of custom Types I have a method to build the array for the required type. It works for the primitive types. But when I have array of custom objects it doesn't work. So I have tweaked it. But still it fails. Code is like this : private Object buildArray( String type, Object object) { final Class<?> requiredType = loadClass(type); final String typeName = type.substring(2).replace(";", "").trim(); Object[] array = ((Object[]) object); ArrayList<Object> arrayList = new ArrayList<Object>(array.length); for (Object customObj : array) { arrayList.add(castToRequiredType(typeName, customObj)); } return arrayList.toArray(); } In this castToRequiredType : casts the CustomObject to the CustomType where CustomType is a class. And array to be build is of type CustomType. I am stuck at dynamically building the array of CustomType. Any help in this direction is welcome. Thanks in advance. A: Thanks I have solved it using Axis's Array Util For the same
{ "pile_set_name": "StackExchange" }
Q: Center allign Contact Form 7 fields I working on customizing Contact Form 7, but have a issue with allign then centered into place. Only message label is ok positioned, others are left, and its not the same size. I inserted this CSS: .no-touchevents a:hover{text-decoration:none;} a:active{background-color:transparent;} input, textarea, select{ width: 80%; display: block; margin: auto; } This CSS only increase width for dropdown label, but not make centered. How to make all fields from contact form centered, and with same width? Site where i work on contact form is link. A: You should add max-width and margin: 0 auto properties to the inputs with class .wpcf7-form-control. Here is the screenshot of how I handled it in the Chrome inspector: http://www.screencast.com/t/ygBP3eQn9jQu
{ "pile_set_name": "StackExchange" }
Q: How to populate RecyclerView with AppWidgetHostViews? I am trying to populate RecyclerView with AppWidgetHostViews but I'm not really sure how to do that. I found a way in which they create a LinearLayout, cast it to ViewGroup and call viewList.add(hostView). I would like to create RecyclerView instead and this is the way I tried: This is my xml: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <View android:id="@+id/appWidget" android:layout_width="match_parent" android:layout_height="wrap_content" /> This is my adapter: public class AppWidgetAdapter extends RecyclerView.Adapter<AppWidgetAdapter.AppWidgetHolder> { private List<View> viewList = new ArrayList<>(); public void setData(List<View> list) { viewList.clear(); viewList.addAll(list); notifyDataSetChanged(); } @Override public AppWidgetHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.app_widget_layout, parent, false); return new AppWidgetHolder(view); } @Override public void onBindViewHolder(AppWidgetHolder holder, int position) { View view = getItem(position); holder.setView(view); } private View getItem(int position) { return !viewList.isEmpty() ? viewList.get(position) : null; } @Override public int getItemCount() { return viewList.size(); } class AppWidgetHolder extends RecyclerView.ViewHolder { private View view; AppWidgetHolder(View itemView) { super(itemView); view = (View) itemView.findViewById(R.id.app_widget); } private void setView (View view) { // ? } } } And inside my fragment: private List<View> viewList = new ArrayList<>(); mAdapter = new AppWidgetAdapter(); mRecycler.setLayoutManager(new LinearLayoutManager(getActivity())); mRecycler.setAdapter(mAdapter); viewList.add((View) event.eventObject); mAdapter.setData(viewList); Event object is AppWidgetHostView.. I don't know how to cast it to bind it in onBindViewHolder() method... Is there a method in View object I can call to pass it AppWidgetHostView, like ViewGroup has add() method? A: I found a solution, maybe it's not the best way, but it works.. I replaced View with FrameLayout inside XML, and changed my ViewHolder: class AppWidgetHolder extends RecyclerView.ViewHolder { private FrameLayout view; AppWidgetHolder(View itemView) { super(itemView); view = (FrameLayout) itemView.findViewById(R.id.app_widget); } private void setView (View view) { if(view.getParent() != null) { ((ViewGroup)view.getParent()).removeView(view); } this.view.addView(view); } }
{ "pile_set_name": "StackExchange" }
Q: Computing the unit normal vector - Simplifying help I have a surface $$X(u,v) = \left(3uv^2 - u^3 - \frac{u}{3}, 3u^2v - v^3 - \frac{v}{3}, 2uv \right), $$ and the cross product $$(X_u \times X_v) = \left(3(u^2 + v^2) \frac{1}{3} \right) \cdot \left(2v, 2u, \frac{1}{3} - 3(u^2 + v^2) \right).$$ I have to show that the unit normal vector is $$N(u,v) = \frac{1}{3(u^2 + v^2) + \frac{1}{3}} \cdot \left( 2u, 2v, \frac{1}{3} - 3(u^2 + v^2) \right).$$ So, to find the unit, I just need to divide by $| X_u \times X_v|$ which should end up being $\left( 3(u^2 + v^2) + \frac{1}{3} \right)^2$. So I do this: $$\sqrt{4u^2 + 4v^2 + \left(\frac{1}{3} - 3(u^2 + v^2) \right)^2}$$ $$ = \sqrt{4u^2 + 4v^2 + \frac{1}{9} -2(u^2 + v^2) + 9(u^2 + v^2)^2}$$ $$ = \sqrt{2u^2 + 2v^2 + \frac{1}{9} + 9(u^2 + v^2)^2}$$ but I'm stuck on how to simplify this. Expanding the $9(u^2 + v^2)^2$ doesn't really help me much. What should I do? A: Expanding $(3(u^{2} + v^{2}) + \frac{1}{3})^{2}$, we see: $(3(u^{2} + v^{2}) + \frac{1}{3})*(3(u^{2} + v^{2}) + \frac{1}{3}) = 9(u^{2}+v^{2})^{2} + 2*3*\frac{1}{3}(u^{2} + v^{2}) + \frac{1}{9}$; Does this help?
{ "pile_set_name": "StackExchange" }
Q: MongoDb : Issue using $divide and $gte I am new to MongoDb. I have problem When i using $divide and $gte below code don't give me error. But it's filter is not working. Code : var filter1 = new BsonDocument() { {"expr", new BsonDocument(){ { "$gte", new BsonArray{ new BsonDocument{ { "$divide", new BsonArray{"$nA", "$wT"} }, }, sPacketMSItem.FromDPC.Value } } } } }; If anyone reuquire more information than tell me. Exception : {MongoDB.Driver.MongoCommandException: Command find failed: unknown top level operator: $expr. at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol1.ProcessReply(ConnectionId connectionId, ReplyMessage1 reply) at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol1.ExecuteAsync(IConnection connection, CancellationToken cancellationToken) at MongoDB.Driver.Core.Servers.Server.ServerChannel.ExecuteProtocolAsync[TResult](IWireProtocol1 protocol, CancellationToken cancellationToken) at MongoDB.Driver.Core.Operations.CommandOperationBase1.ExecuteProtocolAsync(IChannelSource channelSource, ICoreSessionHandle session, ReadPreference readPreference, CancellationToken cancellationToken) at MongoDB.Driver.Core.Operations.ReadCommandOperation1.ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) at MongoDB.Driver.Core.Operations.FindCommandOperation1.ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) at MongoDB.Driver.Core.Operations.FindOperation1.ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) at MongoDB.Driver.OperationExecutor.ExecuteReadOperationAsync[TResult](IReadBinding binding, IReadOperation1 operation, CancellationToken cancellationToken) at MongoDB.Driver.MongoCollectionImpl1.ExecuteReadOperationAsync[TResult](IClientSessionHandle session, IReadOperation1 operation, ReadPreference readPreference, CancellationToken cancellationToken) at MongoDB.Driver.MongoCollectionImpl1.UsingImplicitSessionAsync[TResult](Func2 funcAsync, CancellationToken cancellationToken) at MongoDB.Driver.IAsyncCursorSourceExtensions.ToListAsync[TDocument](IAsyncCursorSource1 source, CancellationToken cancellationToken) at Biz.DAL.MongoRepositoriesCustom.SalesCRMRepository.MarketSheet.MarketSheetRepository.SearchBySearchPacketMSItemAsync(SearchPacketMSItem sPacketMSItem) in /Users/lalitdevani/Documents/AasthaSalesWebApi/Aastha/_git/Sales.WebApi/Biz.DAL/MongoRepositoriesCustom/SalesCRMRepository/MarketSheet/MarketSheetRepository.cs:line 142} Any Help will be appreciated. A: $expr is an Evaluation Query Operator so it should be prefixed with dollar sign, try: var filter1 = new BsonDocument() { {"$expr", new BsonDocument(){ { "$gte", new BsonArray{ new BsonDocument{ { "$divide", new BsonArray{"$nA", "$wT"} }, }, sPacketMSItem.FromDPC.Value } } } } }; EDIT: $expr is available in MongoDB 3.6 or higher, as a fallback you can use $redact, try: var redact = new BsonDocument() { {"$redact", new BsonDocument { { "$cond", new BsonDocument(){ { "if", new BsonDocument() { { "$gte", new BsonArray { new BsonDocument{ { "$divide", new BsonArray{"$nA", "$wT"} }, }, sPacketMSItem.FromDPC.Value } } } }, { "then", "$$KEEP" }, { "else", "$$PRUNE" } } } } } }; var result = Col.Aggregate() .AppendStage<BsonDocument>(redact).ToList();
{ "pile_set_name": "StackExchange" }
Q: Show "NULL" for null values in ASP.NET MVC DisplayFor Html Helper Is there a way to get an @Html.DisplayFor value to show "NULL" in the view if the value of the model item is null? Here's an example of an item in my Details view that I'm working on currently. Right now if displays nothing if the value of the Description is null. <div class="display-field"> @Html.DisplayFor(model => model.Description) </div> A: yes, I would recommend using the following data annotation with a nullable datetime field in your codefirst model : [Display(Name = "Last connection")] [DisplayFormat(NullDisplayText = "Never connected")] public DateTime? last_connection { get; set; } then in your view : @Html.DisplayFor(x => x.last_connection)
{ "pile_set_name": "StackExchange" }
Q: how to move focus in same level in jquery? can you please tell me how to move focus in same level when focus in top node.Actually I am using jstree and use it API with jquery. Firstly I select any node from the tree view after expanding .Then I press button ,It goes to parent node.if it is top node its parent is "#".Now I need if user don't have parent it start moving focus in same level .? Explain with example; I expand "c" node.Select "c-a" node.Then press button it goes to "c" node (As expected it goes to it parent).But now when user again press it stop moving it shoulb move to "b" then "a".. http://jsfiddle.net/fuu94/176/ $('#onelvel').click(function () { if($('.jstree-clicked').length){ if($('.jstree-clicked').next('.jstree-children').length){ $('.jstree-clicked').click(); } else { $('.jstree-clicked').closest('.jstree-children').prev('.jstree-anchor').click().addClass('jstree-clicked'); } } var selectedItem= $('.jstree-clicked').parent().attr('id'); alert(selectedItem) var parentS= $('#tree').jstree(true).get_parent(selectedItem.toString()); alert(parentS) if(parentS=="#"){ alert("on b want to go a") }else{ alert("going uper node") } }); I am checking api from http://www.jstree.com/api/ A: You're getting confused with your selectors and how the jsTree reacts to various elements getting clicked. Have a look at this demo http://jsfiddle.net/XN5JT/1/ Javascript: $('#onelvel').click(function () { selected = $('#tree').jstree(true).get_selected(); parent = $('#tree').jstree(true).get_parent(selected); console.log(selected, parent); if (parent == '#') { $('#' + selected).prev('li').children('.jstree-anchor').click(); } else { $('#' + parent).children('.jstree-anchor').click(); } });
{ "pile_set_name": "StackExchange" }
Q: Azure database became readonly after deploying server to Azure I have got an SQL database on Azure. When connecting to the DB from my Visual Studio, everything is fine. However, once I published the app to Azure, the database became read only. I can fetch the data, but cannot write anything. The server returns 500 code, but I did not any way of debugging it. Could you advice of the solution? A: Alright, I figured out the problem. I debugged the server remotely (luckily it is possible) and found out that the exception was thrown when trying to parse IP address (it is my code). Azure server has got ip:port and my code could only handle ip (without port). So I fixed it and it works.
{ "pile_set_name": "StackExchange" }
Q: Do people have the ability to truly love God, without God guiding them into loving him? From this answer: Secondly, men do not hate God because of the world he created, they hate God because he is good and they are not. However consciously or unconsciously, they hate him because he is altogether different than they are. They do not understand him and if they did they would not like what they found. The Bible teaches that men love darkness because their deeds are dark and that God is light. (John 3:16-20) Men will naturally hate that which brings judgement to their deeds. So people are created sinners and they naturally hate God, right? They could try to love God under the influence of teaching but it's just forced change of their nature through mind (so to speak) and when they experience lots of suffering, it is going to break them at some point and they will realize that they don't really feel the love. Unless of course God has blessed them to love him, in which case they will feel the unconditional love for God. But they have no influence here. Those who (through God's intervention in giving them a new heart) chose to hate sin and love God on earth ... So ultimately only a divine intervention can make a person love God? A: Here is how I would explain the viewpoint behind the comments you quote in your question. I do hold a belief about the nature of people that says that since the fall they are inherently bad, totally corrupt. This doesn't mean they were created that way, just that the corruption that we inherit from the first Adam is so complete that we can do nothing truly good or right on our own volition. This is commonly known as the doctrine of Total Depravity. You might check the entry on Theopedia, and articles such as this or this for an overview of how this doctrine is derived from Scripture. Rather than defend that doctrine here, I simply want to point out that your question hinges on it. You ask: So ultimately only a divine intervention can make a person love God? To answer this, one possible way of defining what it looks like for a human to love God would be this way: John 14:15 “If you love me, you will keep my commandments. Yet if we apply this simple test to humanity and ask, "Do they keep his commandments?" we are left with the bleak conclusion that there are indeed none who keep God's commandments as God intended. Romans 3:12 All have turned aside; together they have become worthless; no one does good, not even one. Of course that isn't the end of the story. Again your question posed whether only a divine intervention can make a person love God. Christianity's answer to that is yes, and that divine intervention has taken place. That divine intervention is very poetically prophesied about in Ezekiel. Ezekiel 11:19-20 And I will give them one heart, and a new spirit I will put within them. I will remove the heart of stone from their flesh and give them a heart of flesh, that they may walk in my statutes and keep my rules and obey them. And they shall be my people, and I will be their God. This is grace. Unmerited favor: a divine intervention to transform undeserving fallen humans into creatures capable of loving that which they once hated. There are of course Christian traditions that do not hold this view. Perhaps most notably, Catholicism has a different take on the issue. While they agree that man in his fallen state is incapable of doing any works that could affect his salvation apart from the Grace of Jesus, they disagree on how total the fallen state is concluding that the heart of men is not really dead to God, only wounded. While they understand salvation to be affected by God, they think man is capable of acting as an initiator in this process. Likewise several Protestant traditions hold that man in his fallen state is still capable of making some good choices. In doing so, Reformed Theology would argue, they replace some aspect of grace with some aspect of works. If men can and do in their natural state "choose" to love God and that makes them eligible for salvation, salvation ceases to be purely a grace bestowed by God and his sovereign will in the matter becomes eclipsed by ours to whatever measure men are thought to be capable of deserving anything.
{ "pile_set_name": "StackExchange" }
Q: My php echo statements do not output expected array contents from SQL query I have the following code which selects ID's of a database with many regions in it. I create the array as follows: $old2 = $this->query("SELECT regionid FROM theregions WHERE regionparent = '808'"); $old2_array = mysqli_fetch_array($old2); And then I try and output the array like so: while($row = mysqli_fetch_array($old2)) { echo $row[0] . '<br>'; } It produces the following: 800 834 933 However, if I use phpMyAdmin and run the same SQL statement, I get: 604 800 834 933 If I try using print_r(array_values($old2_array)); I get: Array ( [0] => 604 [1] => 604 ) Have searched many SO pages, and have tried this: $length = count($old2_array); for ($i = 0; $i < $length; $i++) { echo $old2_array[$i], "<br />"; }; ...which produces: 604 Notice: Undefined offset: 1 in /index.php on line 128 A: The answer is not to have that second line. Once I remove this: $old2_array = mysqli_fetch_array($old2); Then the following loop works: while( $reg = $old2->fetch_object() ) { echo $reg->region_id . "<br>"; } For some reason, the mysqli_fetch_array() statement screws with following commands.
{ "pile_set_name": "StackExchange" }
Q: C# Process.Start для pdf файла возвращет false Столкнулся с такой проблемой, имеется код для запуска для редактирования того или иного файла, все работает, однако есть проблема с pdf файлом. При вызове метода Process.Start файл открывается, но метод возвращает false почему-то. Проблема наблюдается только с pdf файлами. Кто-нибудь сталкивался с таким? var currentProcess = new Process { StartInfo = { UseShellExecute = true, CreateNoWindow = true, FileName = fileWatch.FilePath, } }; A: Вы бы указали, какую именно перегрузку Process.Start использовали. Судя по вопросу, ту, которая возвращает bool. Цитата из документации: Возвращаемое значение Boolean Значение true, если ресурс процесса запущен; значение false, если новый ресурс процесса не был запущен (например, при повторном использовании существующего процесса). Следовательно, процесс используется повторно.
{ "pile_set_name": "StackExchange" }
Q: Swift no option to add an Ob-C bridging header file under Build Options I have added some Objective C files to my Swift project using Cocoapods. I created a Bridging-Header.h file using File->New->File IOS Source Header File. It is in the project. See screen shot with project files on left. I now need to add that file to the Project Build Settings -> Swift Compiler - Code Generation. The problem is (see screen shot) that the option to add the Bridge file does not exist!!! ??? I cannot find a reference to a problem like this anywhere on the web, cocoapods or apple. Can anyone suggest a way to get the option to add the bridging file appear in the Build Settings A: You have to click on "ALL" tab. If you take a look to your picture, you're on "Basic", switching to "ALL" should do the trick.
{ "pile_set_name": "StackExchange" }
Q: Mouse Move Capture (Mouse leave & Mouse Enter) Hi i have three controls (CButtton) in my application,whenever mouse move over a control,i want to capture when mouse enters on which control in a window and when it leaves and i have to change the caption of a button control. Thanks in Advance A: There is no windows message/event that indicates 'mouse enter' or 'mouse leave'. However this can be achieved by handling the 'MouseMove' message for your control and capturing the mouse input to check if the point is inside the control area. Release the capture if the point is out of the control area. for sample code check here.
{ "pile_set_name": "StackExchange" }
Q: Assign a sub class to an interface, with generics and covariant involved I defined 3 interfaces: public interface IManufacturerInput { } public interface IManufacturerOutput { } public interface IManufacturerApi<in S, out T> where S : IManufacturerInput where T : IManufacturerOutput { T Calculate(S); } And I defined a specific Manufacturer: public class ManufacturerAInput : IManufacturerInput { } public class ManufacturerAOutput : IManufacturerOutput { } public class ManufacturerAApi : IManufacturerApi<ManufacturerAInput, ManufacturerAOutput> { public ManufacturerAOutput Calculate(ManufacturerAInput) { return null; } } And In Main() I created a ManufacturerAApi, and try assign it to IManufacturerApi. IManufacturerApi<IManufacturerInput, IManufacturerOutput> api = new ManufacturerAApi(); But it failed. The error message said (just abstract meaning): Can't convert from ManufacturerAApi to IManufacturerApi<IManufacturerInput, IManufacturerOutput> So is there any way I can make the assignment work? Thanks in advance. A: What you are proposing isn't type safe. Let's change the names of your types to make the issue clearer: public interface IPetFood { } public interface IPetSound { } public interface IPetCage<in S, out T> where S : IPetFood where T : IPetSound { T Feed(S s); } public class DogFood : IPetFood { } public class CatFood : IPetFood { } public class Bark : IPetSound { } public class DogCage : IPetCage<DogFood, Bark> { public Bark Feed(DogFood input) { return new Bark(); } } And now suppose this is legal: IPetCage<IPetFood, IPetSound> api = new DogCage(); Then we could do the following: api.Feed(new CatFood()); //oops we've just given the dog some catfood. The assignment will not work because S is contravariant, which means that any possible IPetFood passed into api.Feed would need to be a subtype of DogFood and you have the opposite; IPetFood is a superset of DogFood.
{ "pile_set_name": "StackExchange" }
Q: What is the maximum number of sensors that can be operated on a single Aurdino unit I currently have an Aurdiuno uno and a motor driver shield: (http://www.hobbytronics.co.uk/arduino-motor-shield). Now, I would like to run the following mechatronic devices: 3 bi-direction motors, 1 servo, 1 hall effect sensor (digital), 2 infra-red sensors, 1 magnetometer, 1 ultrasonic sensor, Will the Aurdiuno uno paired with the motor sheild be able to run these components or will I need to buy an Aurdiuno mini? Could I please gain some insight into how you figure out what pins are required and how would i connect the sensor pins to the motor sheild since it does not have any direction slip on connections like the Aurdiuno Uno. Will I need to solder the sensor connections on? Thankyou A: Will the Aurdiuno uno ... buy an Aurdiuno mini? The main differences between the uno and mini are: footprint 6 (uno) vs 8 (mini) analog inputs You will get two extra analog inputs and a much smaller size at the cost of the shield not fitting anymore. Now, I would like to run the following mechatronic devices: 3 bi-direction motors, 1 servo, 1 hall effect sensor (digital), 2 infra-red sensors, 1 magnetometer, 1 ultrasonic sensor, Will the Aurdiuno uno paired with the motor sheild be able to run these components? According to the website the shield supports up to 4 motors or 5 servos, so i would guess that it would work. if the shield can't do 3 motors and 1 servo at the same time, then you can just use the servo library and a pin for that. The shield requires 3 pins to function; so you need 3 or 4 pins depending on configurations. Inputs 1 digital, 4 analog; 1 Digital I\O, 1 Analog In so it looks like you need 4-5 DIO pins and 4 analog pins, which the uno has so yes. If you were using motor driver boards instead of a shield the cost would be 2x PWM per Motor/driver combo = 6 PWM 1 DIO for servo 1 DIO for digital input 4x Analog Inputs Which also fits in the budget all 6 of the PWM DIO pins, + 2 more (leaving 6 of the 14) and 2/3rds of the analog pins (also good you can leave A3,4 alone since they share a timer and only use the other ones)
{ "pile_set_name": "StackExchange" }
Q: Нужна помощь Си Суть проги в том что она выводит в последние буквы каждых слов строки. Я написал прогу без доп. функции и все работает, но мне нужно с функцией. Вот код: #include <stdio.h> #include <string.h> #include <ctype.h> void last_char(char str); void last_char(char str){ int i; int flag = 0; for( i = 0; str[i]; ++i ) { if( isspace(str[i]) ) { if( flag ) printf("%c", str[i - 1]); flag = 0; } else flag = 1; } if( flag ) printf("%c", str[i - 1]); } int main(void){ char *str[256]; printf("> "); scanf("%255[^\n]", str); last_char(str); } Выводит следующие. ошибки: 10:error: subscripted value is neither array or pointer. 11:error: subscripted value is neither array or pointer. 13:error: subscripted value is neither array or pointer. 21:error: subscripted value is neither array or pointer. Я новичок в программировании, прошу, помогите! A: void last_char(char *str){ ... int main(void){ char str[256];
{ "pile_set_name": "StackExchange" }
Q: Custom filter for short and full name in angularjs I want to create a filter that could filter by short name and full name I have done it by full name angular.module('myApp', []).controller('namesCtrl', function($scope) { $scope.names = [ 'Indian Overseas Bank', 'Housing Development Finance Corporation', 'Industrial Credit and Investment Corporation of India', 'Indian Bank', 'City Bank', 'City Union Bank', 'Kotak Mahindra Bank', 'Tamilnadu Mercantile Bank ', 'State Bank Of India' ]; }); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <!DOCTYPE html> <div ng-app="myApp" ng-controller="namesCtrl"> <p>Type a letter in the input field:</p> <p><input type="text" ng-model="test"></p> <ul> <li ng-repeat="x in names | filter:test"> {{ x }} </li> </ul> </div> But I am not sure, how can I filter by short name like IOB, HDFC, SBI? I want to the result to be like Filter word : Expected result IOB : Indian Overseas Bank HDFC : Housing Development Finance Corporation SBI : Stete Bank of India ICICI : Industrial Credit and Investment Corporation of India' Note : Those banks are Indian banks. See, when I do filtering by SBI and ICICI then filter won't recognize of, and words. Also if I am typing normal word like india, then I am expecting the results to be filtered by india same as I have done in the snippet . How could do this? A: Clearly you need a custom filter. Your job is to break words into abbreviations. Then you can simply match the model to your abbreviations as a normal filter would, I suggest .indexOf() method. Here is my simple demo: var app = angular.module('myApp', []); app.filter('myFilter', function() { return function(inp, model) { if (!model) { return inp; } var ignore = ["of", "and", "Of", "And"]; var array = []; for (var i = 0; i < inp.length; i++) { var str = ""; var arr = inp[i].split(" "); for (var j = 0; j < arr.length; j++) { if (ignore.indexOf(arr[j]) == -1) { str += arr[j][0]; } } // str = str.toLowerCase(); // model = model.toLowerCase(); if (str.indexOf(model) != -1) { array.push(inp[i]); } } return array; }; }); app.controller('namesCtrl', function($scope) { $scope.names = [ 'Indian Overseas Bank', 'Housing Development Finance Corporation', 'Industrial Credit and Investment Corporation of India', 'Indian Bank', 'City Bank', 'City Union Bank', 'Kotak Mahindra Bank', 'Tamilnadu Mercantile Bank ', 'State Bank Of India' ]; }); <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="namesCtrl"> <p>Type a letter in the input field:</p> <p><input type="text" ng-model="test"></p> <ul> <li ng-repeat="x in names | myFilter:test"> {{ x }} </li> </ul> </div> </body> </html> (The example is case sensitive)
{ "pile_set_name": "StackExchange" }
Q: Memory accumulation with PHP SoapClient using call() method When I use the call() method of the SoapClient class in loop it seems to be building up memory. I have tried to search for solutions on the internet and some of the answers are to disable WSDL Cache, but it did not work for me. I have tried disabling cache with ini_set("soap.wsdl_cache_enabled", 0) and as a parameter of the SoapClient class instance. I have tried ini_set("soap.wsdl_cache_ttl", 0). I also have tried unset($this->_client) and unset($this->_session). Nothing worked for me. ini_set("soap.wsdl_cache_enabled", WSDL_CACHE_NONE); private function _call($method, $params = null) { if (is_null($this->_client)) { $soapParams = array( 'cache_wsdl' => WSDL_CACHE_NONE ); $this->_client = new SoapClient($this->_getConfig('api/url'), $soapParams); $this->_session = $this->_client->login($this->_getConfig('api/user'), $this->_getConfig('api/key')); } $memoryBefore = memory_get_usage(); echo "\n" . 'Memory Usage Before: ' . number_format($memoryBefore, null, '', '.'); $result = $this->_client->call($this->_session, $method, $params); $memoryAfter = memory_get_usage(); echo "\n" . 'Memory Usage After: ' . number_format($memoryAfter, null, '', '.'); echo "\n" . 'Memory Usage Difference: ' . number_format($memoryAfter - $memoryBefore, null, '', '.') . "\n"; return $result; } Is there any way to solve that? Am I doing something wrong? I'm running the following method via the command line (using PHP 5.3.29) $ php -f datasync.php Memory Usage Before: 13.244.400 Memory Usage After: 20.239.488 Memory Usage Difference: 6.995.088 Importing Orders... 1% [100/6055] - Page number (pagenum): 1 Page size (pagesize): 100 Total pages: 61 Memory Usage Before: 22.402.792 Memory Usage After: 29.519.432 Memory Usage Difference: 7.116.640 3% [200/6055] - Page number (pagenum): 2 Page size (pagesize): 100 Total pages: 61 Memory Usage Before: 29.519.984 Memory Usage After: 36.515.112 Memory Usage Difference: 6.995.128 4% [300/6055] - Page number (pagenum): 3 Page size (pagesize): 100 Total pages: 61 Memory Usage Before: 36.515.680 Memory Usage After: 43.723.440 Memory Usage Difference: 7.207.760 6% [400/6055] - Page number (pagenum): 4 Page size (pagesize): 100 Total pages: 61 Memory Usage Before: 43.724.056 Memory Usage After: 50.879.592 Memory Usage Difference: 7.155.536 8% [500/6055] - Page number (pagenum): 5 Page size (pagesize): 100 Total pages: 61 Memory Usage Before: 50.880.096 Memory Usage After: 58.083.616 Memory Usage Difference: 7.203.520 9% [600/6055] - Page number (pagenum): 6 Page size (pagesize): 100 Total pages: 61 Memory Usage Before: 58.084.232 Memory Usage After: 65.167.136 Memory Usage Difference: 7.082.904 11% [700/6055] - Page number (pagenum): 7 Page size (pagesize): 100 Total pages: 61 A: The problem was something else. I'm sorry. I tried to isolate everything to find out where the code was consuming memory but I forgot a function executing recursively. The solution was to replace recursively methods with do-while. See: PHP: Memory leak in recursive function I was using this: foreach ($result['items'] as $data) { $datasyncOrder->saveOrder($data, $this->_useOriginalIds); $this->_clv->printProgress($pageNumber, $result['pagesize'], $result['pages'], $result['page'], $result['total'], $index); $index++; } if ($result['page'] < $result['pages']) { $newResult = $this->_call('datasync.orders_export', array($result['page'] + 1, $result['pagesize'])); $this->_importOrders($newResult, $pageNumber, $index); } I replaced with: $originalPageNumber = $pageNumber; do { try { if ($originalPageNumber == $pageNumber) { $this->_clv->printString(Mage::helper('datasync')->__('Loading Orders...') . "\n"); } $result = $this->_call('datasync.orders_export', array($pageNumber, $pageSize)); if ($originalPageNumber == $pageNumber) { $this->_clv->printString(Mage::helper('datasync')->__('Importing Orders...') . "\n"); } $index = 1; foreach ($result['items'] as $data) { $datasyncOrder->saveOrder($data, $this->_useOriginalIds); $this->_clv->printProgress($pageNumber, $result['pagesize'], $result['pages'], $result['page'], $result['total'], $index); $index++; } $pageNumber++; } catch (Exception $e) { $this->_setOriginalEntityIncrementInfo('order', Mage::getModel('eav/config')->getEntityType('order')->getEntityTypeId(), $this->_storeId); } } while ($result['page'] < $result['pages']);
{ "pile_set_name": "StackExchange" }
Q: What is the datatype of &(char *) in C? Suppose I have char *t = "XX"; I am wondering what is the type of &t. Is it char or array? A: Since t is a pointer, &t is a pointer to a pointer. A: The type of &t for any expression is a pointer to the type of t. In this case the type of t is char* hence the the type of &t is char**
{ "pile_set_name": "StackExchange" }
Q: Android: Image button is not alligned to right I want my image button to be placed on the rt side bottom of the scree. but it is not getting visible.Please see the code. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TableLayout android:id="@+id/tableLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical" > <TableRow android:id="@+id/tableRow1" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Date of Birth:" /> <Button android:id="@+id/dateButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null" android:text="Select date" /> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Manual labour" /> <EditText android:id="@+id/ed1" android:layout_width="120dp" android:layout_height="wrap_content" android:inputType="number" /> </TableRow> <TableRow android:id="@+id/tableRow3" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Gender :" /> <RadioGroup android:id="@+id/radioSex" android:layout_width="wrap_content" android:layout_height="wrap_content" > <RadioButton android:id="@+id/radioMale" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="Male" /> <RadioButton android:id="@+id/radioFemale" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Female" /> </RadioGroup> </TableRow> <TableRow android:id="@+id/tableRow4" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Occupation" /> <Spinner android:id="@+id/spinner1" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/occuaption_arrays" android:prompt="@string/occupation_prompt" /> </TableRow> <TableRow android:id="@+id/tableRow5" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Monthly Income" /> <Spinner android:id="@+id/spinner2" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/income_arrays" android:prompt="@string/income_prompt" /> </TableRow> </TableLayout> <ImageButton android:id="@+id/next" android:layout_height="50dp" android:layout_width="50dp" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" android:contentDescription="dfg" android:src="@drawable/next" android:visibility="visible"/> I have tried using RelativeLayout as parent and add attribute android:layout_alignParentRight="true" and android:layout_alignParentBottom="true" My image is very large.Is that can be a problem? A: You have setted match-parent to width and height of TableLayout. So TableLayout overlaps ImageButton use below code... android:layout_width="match_parent" android:layout_height="wrap-content"
{ "pile_set_name": "StackExchange" }
Q: 2D XNA game Camera issue I'm currently making a 2D Worm-clone in XNA, and have regrets about the way I've made my camera. I declare my camera in my Main class and the camera follows the player. In my draw I then begin my spritebatch using my camera transformations. The problem is, EVERYTHING needs to be drawn in Main because they need to be drawn under the camera transformations (unless I send the camera to each classes constructor). My question is, is there a way to make it so the Camera is basically global over my whole program, everything is "by default" affected by it? Or at least so it's not only in Main and I can have things that draw themselves. I've searched for tutorials, but they all explain how to make the camera and to implement it in one draw function, not over a whole program with many different entities. A: OK, so when you say "Main" I am imagining you mean the class that you derive from Game? There is nothing wrong with calling SpriteBatch.Begin() multiple times around your program and passing in your camera matrix to each one. Presumably each of your gameplay classes has a Draw method? I recommend passing either your camera matrix or a class containing your camera matrix into each Draw function you are calling. So your Draw function in your game class might look like this: protected override void Draw(GameTime gameTime) { player.Draw(spriteBatch, camera); foreach(var enemy in enemies) enemy.Draw(spriteBatch, camera); } If your gameplay classes are DrawableGameComponents, well this is a really good reason not to use game components! Of course, if you insist on using DGC, then passing a camera class to each constructor, as you mention, will work. But as you've probably discovered, it means you have to figure out how to store it in each class - along with quite a bit of code duplication to do so. You could also use the Services architecture to allow your components to access the camera. But like DGC, this is a very "heavy" architecture. Why write and manage a service, when you can just make your camera global by making it a public static member of your game class? (It's gameplay code. It doesn't have to be fancy. DTSTTCPW.) A: I'm afraid I have to disagree with Andrew on this one. I do recommend the DrawableGameComponent architecture and I would dispute that this, or the services pattern, are particularly 'heavyweight' - I do have other issues, outside of the scope of this question, but performance generally isn't one of them. Creating a single camera object to provide a view and projection matrix to your drawables is straightforward and allows you to have your objects draw themselves in their own Draw method. This is, by far, the most common way of structuring an XNA project in my experience. At the end of the day your drawables are only maintaining a reference to a single object, so there is not much overhead. How you provide this reference is a matter of taste and whether you are bothered about reusing your code in other projects: You can offer the camera through the services pattern and get hold of it in your drawable's Initialize method. Pass it in during construction (provided it has already been instansiated). Use a public Property of your derived game class (which you retrieve by casting the Drawable's game object reference to the derived game type first) Use a Static, as Andrew suggests. Personally I would suggest one of the first 2 options (via an ICamera interface definition) to neatly decouple your actual camera & drawable implementations for later re-use. Personally I don't believe well structured code is 'fancy' - good code is just good code.
{ "pile_set_name": "StackExchange" }
Q: Angular isolated scope values not visible in template when using replace I am creating a small app and I have the following directive with the template. smallgrid.directive.js: angular.module('myActions') .directive('smallgrid', ['$rootScope', function($rootScope) { return { restrict: "E", scope: { actionable: "=" }, controller: function($scope) { $scope.setLocation = function() { console.log("yee"); }; } }; }]) .directive('three', function() { return { replace: true, templateUrl: '/app/my_actions/directives/templates/grid3x3.template.html' }; }) .directive('four', function() { return { replace: true, templateUrl: '/app/my_actions/directives/templates/grid4x4.template.html' }; }) .directive('five', function() { return { replace: true, templateUrl: '/app/my_actions/directives/templates/grid5x5.template.html' }; }); grid3x3.template.html <div class="k-edit-field" id="board"> <div class="row" ng-click="setLocation()"> {{actionable.probability}} </div> </div> I use this directive as follows: <smallgrid three actionable="currentAction.actionable" ng-if="somecondition"></smallgrid> The UI renders properly. However it shows {{actionable.probability}} is empty and the Click event is not firing. However, if I remove the isolated scope and access the variable directly, values are available. I understand that when I am using isolated scopes, in the three directive, I can't access values of smallgrid. Is there a way to pass those values from smallgrid to the template? A: Passing a directive as an attribute of a directive you're bound to have scope problems. It will look better if you use scope inheritance for nested directives with ng-transclude. So your starting point should be <smallgrid actionable="currentAction.actionable" ng-if="somecondition"> <three></three> </smallgrid> This way <three> has access to the $parent function smallgrid() { return { restrict: "E", transclude: true, scope: { actionable: "=" }, template: `<div ng-transclude></div>`, controller: function($scope) { $scope.setLocation = function() { console.log("yee"); }; } }; } function three() { return { template: `<div class="k-edit-field" id="board"> <div class="row" ng-click="$parent.setLocation()"> test = {{$parent.actionable.probability}} </div> </div>` }; } function myController($scope) { $scope.currentAction = {actionable: {probability: "test"}}; $scope.somecondition = true; } angular.module('myApp', []); angular .module('myApp') .controller('myController', myController) .directive('smallgrid', smallgrid) .directive('three', three); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <div ng-app="myApp"> <div ng-controller="myController"> <smallgrid actionable="currentAction.actionable" ng-if="somecondition"> <three></three> </smallgrid> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: Formatting timestamp results in strange output Input: 1457690400000 Call: moment.unix(1457690400000).format('DD-MM-YYYY HH:mm') Expected output: 11-03-2016 03:00 Actual output: 15-05-48162 10:00 I cannot figure out why this is happening. Is this a bug? A: I think you are getting confused with the unix() method in momentjs. Have you tried: moment(1457690400000).format('DD-MM-YYYY HH:mm ZZ') which for me outputs 11-03-2016 11:00 +0100 since I'm in CET. Verified the result with http://www.epochconverter.com/
{ "pile_set_name": "StackExchange" }
Q: jQuery SmoothDivScroll - endlessloop works with images but not text in a list Here is the default SmoothDivScroll demo but with endlessloopright, everything works fine: http://smartpeopletalkfast.co.uk/smoothdivscroll/jQuery%20Smooth%20Div%20Scroll%20by%20Thomas%20Kahn%20-%20smooth%20content%20scrolling%20using%20jQuery.html Here all ive done is replace the images with text in a list. It does scroll but it doesn't loop: http://smartpeopletalkfast.co.uk/smoothdivscroll/LIST%20-%20jQuery%20Smooth%20Div%20Scroll%20by%20Thomas%20Kahn%20-%20smooth%20content%20scrolling%20using%20jQuery%20copy.html Anyone have an idea why this is happening? Thanks A: It works if I put the text in divs, not in a list.
{ "pile_set_name": "StackExchange" }
Q: insert tab separated records to sql server Is there any tool which can read a text file and insert the records that separated by tab characters in the file to a sql server table. i can do that by developing a small c# application but i wonder if there is already a tool doing that. A: You can use bulk insert: Have a look at this SO post: Import .txt file to SQL Server 2008 and SQL SERVER – Import CSV File Into SQL Server Using Bulk Insert – Load Comma Delimited File Into SQL Server Best Regards
{ "pile_set_name": "StackExchange" }
Q: Filter out chars not in a set I am trying to filter all strings that I pass through my system, so that I only send out valid chars. The following are allowed. a-z A-Z "-" (hypen, 0x24) " " (space, 0x20) "’" (single quote, 0x27) "~" (tilde, 0x7E) Now I can come up with a regex that searches for chars in this set. But What I need is a regex that matches to chars out of this set so I can replace them with nothing. Any ideas? A: Here is a way you can do it. You tagged Perl, so i will give you a perlish solution: my $string = q{That is a ~ v%^&*()ery co$ol ' but not 4 realistic T3st}; print $string . "\n"; $string =~ s{[^-a-zA-Z '~]}{}g; print $string . "\n"; Prints: That is a ~ v%^&*()ery co$ol ' but not 4 realistic T3st That is a ~ very cool ' but not realistic Tst To make it clear: $string =~ s{[^-a-zA-Z '~]}{}g; matches for chars who are not [^..] inside the [,] parenthesis and replace them with nothing. The g flag at the end of the substitution is for replacing more than 1 character.
{ "pile_set_name": "StackExchange" }
Q: switching between solar input and 5V supply I am designing an energy harvesting system from a low power solar panel. I am using the output of the solar panel to power a high efficiency boost converter which charges a single cell Lithium battery as shown in the diagram below. My question is what is the best way to modify my circuit to switch between the solar input and an external 5V supply. Ordinarily I would use a diode in series with each of the supplies to switch between the inputs to the boost converter however given the extreme low power needs of the circuit I may not be able to afford the losses across the diode. A: The BQ25504 datasheet says the maximum input voltage at VBAT might be 5.5V. Make sure you don't exceed that and just connect your charger circuitry to the battery in parallel. Battery chargers will have a high output impedance when not powered externally (because they'd otherwise drain the battery), so this will not be a problem. It might look comfortable to put the 5V supply on the input, but don't: The peak power the BQ25504 will sustain is 400mW, and it's not recommend to charge with more than 300mW flowing through the device (*recommended operation conditions in the datasheet). So, your battery will charge really slow. When you attach 5V, you'll probably just want the battery charged as fast as possible; so invest a couple of cents in one of the hundreds of LiIon Charger ICs and attach that to your battery.
{ "pile_set_name": "StackExchange" }
Q: NSOutlineView drag promises with directories How does one implement an NSOutlineViewDataSource to allow dragging directories that do not exist in the file system at the time of dragging to the Finder? I have searched and searched and read a ton of the documentation, but have had great difficulty finding anything of value that works. I use a custom data source that manages a file system-like tree, and all the items are instances of a class that keeps track of its path. I would like to be able to drag files and directories out of the outline view into the Finder. I have: - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pasteboard { NSMutableArray *types = [NSMutableArray array]; for (JOItemInfo *itemInfo in items) { NSString *extension = itemInfo.name.pathExtension; if (extension.length > 0) [types addObject:extension]; } [pasteboard declareTypes:@[(__bridge_transfer NSString *)kPasteboardTypeFileURLPromise] owner:self]; [pasteboard setPropertyList:types forType:(__bridge_transfer NSString *)kPasteboardTypeFileURLPromise]; DDLogInfo(@"Wrote types %@ to pasteboard %@ for key %@", types, pasteboard, (__bridge_transfer NSString *)kPasteboardTypeFileURLPromise); return YES; } and an implementation of -outlineView:namesOfPromisedFilesDroppedAtDestination:forDraggedItems: that writes the items inside of the given path. This works in that I can drag items out to the Finder, but when I let go nothing else happens, and the -...namesOfPromisedFilesDropped... method isn't even called. Also, [self.outlineView setDraggingDestinationFeedbackStyle:NSTableViewDraggingDestinationFeedbackStyleRegular]; [self.outlineView setDraggingSourceOperationMask:NSDragOperationNone forLocal:YES]; [self.outlineView setDraggingSourceOperationMask:NSDragOperationCopy forLocal:NO]; is in my -awakeFromNib. The if (extension.length > 0) ... was based on an example I found somewhere, but it was dated, and the documentation says to return an extension, so I think that is appropriate. Personally, I find the documentation for this whole area very lacking, especially in regard to an NSOutlineView. Thanks! A: I changed (__bridge_transfer NSString *)kPasteboardTypeFileURLPromise to NSFilesPromisePboardType, and I can now drag files (with an extension at least) and they can be dropped successfully in the Finder. (I had used the former b/c the documentation for the latter recommended that, but they do not have the same effect.) Also, I tried removing the conditional and allowing it to add an empty string for an empty extension, which worked like a charm. I can now drag out of the outline view into the Finder.
{ "pile_set_name": "StackExchange" }
Q: Ubuntu - slow Image Viewer I have Dell Precision with i7 and Nvidia Quadro 2000M. I have many 12MP (5MB JPEG) images from my camera. Image viewer on ubuntu needs 2-3 seconds to show next image. Windows 7 does the same in no-time, ps3 also, even my IPad is incredibly fast... Is is possible to do something in order to improve performance? Maybe it's possible to enable hardware acceleration? A: Which viewer you used in Ubuntu? In my experience, Shotwell is much faster than the default Image Viewer, as the latter apparently doesn't pre-load next image. Also this is disk operation, so if your Ubuntu running on an old drive and Windows 7 running on SSD that could make the difference too. Cheers, Ray
{ "pile_set_name": "StackExchange" }
Q: Accessing a Collection Through Reflection Is there a way to iterate (through foreach preferably) over a collection using reflection? I'm iterating over the properties in an object using reflection, and when the program gets to a type that is a collection, I'd like it to iterate over the contents of the collection and be able to access the objects in the collection. At the moment I have an attribute set on all of my properties, with an IsCollection flag set to true on the properties that are collections. My code checks for this flag and if it's true, it gets the Type using reflection. Is there a way to invoke GetEnumerator or Items somehow on a collection to be able to iterate over the items? A: I had this issue, but instead of using reflection, i ended up just checking if it was IEnumerable. All collections implement that. if (item is IEnumerable) { foreach (object o in (item as IEnumerable)) { } } else { // reflect over item } A: I've tried to use a similar technique as Darren suggested, however just beware that not just collections implement IEnumerable. string for instance is also IEnumerable and will iterate over the characters. Here's a small function I'm using to determine if an object is a collection (which will be enumerable as well since ICollection is also IEnumerable). public bool isCollection(object o) { return typeof(ICollection).IsAssignableFrom(o.GetType()) || typeof(ICollection<>).IsAssignableFrom(o.GetType()); } A: Just get the value of the property and then cast it into an IEnumerable. Here is some (untested) code to give you an idea: ClassWithListProperty obj = new ClassWithListProperty(); obj.List.Add(1); obj.List.Add(2); obj.List.Add(3); Type type = obj.GetType(); PropertyInfo listProperty = type.GetProperty("List", BindingFlags.Public); IEnumerable listObject = (IEnumerable) listProperty.GetValue(obj, null); foreach (int i in listObject) Console.Write(i); // should print out 123
{ "pile_set_name": "StackExchange" }
Q: Error while copying objects from one S3 bucket to another s3 bucket I am trying to copy objects from one s3 bucket to another s3 bucket, i see below error, aws s3 cp s3://cloud-test/aggs s3://core-templates/ An error occurred (404) when calling the HeadObject operation: Key "aggs/" does not exist A: Try this, aws s3 cp s3://cloud-test/aggs s3://core-templates/aggs/ --recursive
{ "pile_set_name": "StackExchange" }
Q: Python REST API call equivalent in Node.js I've been recently trying to communicate with the UniProt API. As I am starting with Node.js, I have some initial problems, namely: I am trying to conver this python request: import urllib,urllib2 url = 'http://www.uniprot.org/uploadlists/' params = { 'from':'ACC', 'to':'P_REFSEQ_AC', 'format':'tab', 'query':'P13368 P20806 Q9UM73 P97793 Q17192' } data = urllib.urlencode(params) request = urllib2.Request(url, data) contact = "" # Please set your email address here to help us debug in case of problems. request.add_header('User-Agent', 'Python %s' % contact) response = urllib2.urlopen(request) page = response.read(200000) To node.js. My attempt: var params = { 'from':'ACC', 'to':'P_REFSEQ_AC', 'format':'json', 'query':'P13368 P20806 Q9UM73 P97793 Q17192' } var post_data = querystring.stringify(params); var url = 'http://www.uniprot.org/uploadlists/' var options = { uri: url, qs: post_data, method: 'POST' }; urllib.request(options, function (err, data, res) { if (err) { throw err; // you need to handle error } console.log(data.toString()) cb("test") // this doesnt currently matter }); What am I doing wrong? Thank you. A: Using node-rest-client can help you achieve what you are trying. npm i node-rest-client --save I believe you have a starter project for nodejs which contains package.json. var Client = require('node-rest-client').Client; var client = new Client(); var args = { data: { 'from': 'ACC', 'to': 'P_REFSEQ_AC', 'format': 'json', 'query': 'P13368 P20806 Q9UM73 P97793 Q17192' }, headers: { "Content-Type": "application/json"//use the header that you need } }; client.post("http://www.uniprot.org/uploadlists/", args, function(data, response) { // parsed response body as js object console.log(data); // raw response console.log(response); });
{ "pile_set_name": "StackExchange" }
Q: Cannot use combineForms in my existing combineReducers Following the react-boiler-plate project, I want to use react-redux-forms and looking at the 'get started' guide it says to just use combineForms. I tried to figure this out for many hours and the documentation is not helping much. Hope somebody can clue me in to what's happening here. My hours of research has led me to believe that: I have incorrectly used combineForms ImmutableJS cannot be used in conjunction with react-redux-forms Here are my files: configureStore.js: /** * Create the store with dynamic reducers */ import {createStore, applyMiddleware, compose} from 'redux'; import {fromJS} from 'immutable'; import {routerMiddleware} from 'react-router-redux'; import createSagaMiddleware from 'redux-saga'; import createReducer from './reducers'; const sagaMiddleware = createSagaMiddleware(); export default function configureStore(initialState = {}, history) { // Create the store with two middlewares // 1. sagaMiddleware: Makes redux-sagas work // 2. routerMiddleware: Syncs the location/URL path to the state const middlewares = [ sagaMiddleware, routerMiddleware(history), ]; const enhancers = [ applyMiddleware(...middlewares), ]; // If Redux DevTools Extension is installed use it, otherwise use Redux compose /* eslint-disable no-underscore-dangle */ const composeEnhancers = process.env.NODE_ENV !== 'production' && typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ // TODO Try to remove when `react-router-redux` is out of beta, LOCATION_CHANGE should not be fired more than once after hot reloading // Prevent recomputing reducers for `replaceReducer` shouldHotReload: false, }) : compose; /* eslint-enable */ const store = createStore( createReducer(), fromJS(initialState), composeEnhancers(...enhancers) ); // Extensions store.runSaga = sagaMiddleware.run; store.injectedReducers = {}; // Reducer registry store.injectedSagas = {}; // Saga registry // Make reducers hot reloadable, see http://mxs.is/googmo /* istanbul ignore next */ if (module.hot) { module.hot.accept('./reducers', () => { store.replaceReducer(createReducer(store.injectedReducers)); }); } return store; } reducer.js: import { combineReducers } from 'redux-immutable'; import { fromJS } from 'immutable'; import { LOCATION_CHANGE } from 'react-router-redux'; import { createForms, combineForms } from 'react-redux-form/immutable'; import languageProviderReducer from 'containers/LanguageProvider/reducer'; /* * routeReducer * * The reducer merges route location changes into our immutable state. * The change is necessitated by moving to react-router-redux@4 * */ // Initial routing state const routeInitialState = fromJS({ location: null, }); /** * Merge route into the global application state */ function routeReducer(state = routeInitialState, action) { switch (action.type) { /* istanbul ignore next */ case LOCATION_CHANGE: return state.merge({ location: action.payload, }); default: return state; } } const initialUserState = fromJS({ firstName: '', lastName: '', }); /** * Creates the main reducer with the dynamically injected ones */ export default function createReducer(injectedReducers) { return combineReducers({ route: routeReducer, language: languageProviderReducer, forms: combineForms({ user: initialUserState, }, 'forms'), ...injectedReducers, }); } index.js: import React from 'react'; import { Form, Control, } from 'react-redux-form'; export default function App() { return ( <UserForm /> ); } class UserForm extends React.Component { render() { return ( <Form model="user" onSubmit={(user) => this.handleSubmit(user)} > <label>First name:</label> <Control.text model=".firstName" /> <button type="submit"> Finish registration! </button> </Form> ); } } app.js: /** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { ConnectedRouter } from 'react-router-redux'; import FontFaceObserver from 'fontfaceobserver'; import createHistory from 'history/createBrowserHistory'; import 'sanitize.css/sanitize.css'; // Import root app import App from 'containers/App'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-webpack-loader-syntax */ import '!file-loader?name=[name].[ext]!./images/favicon.ico'; import '!file-loader?name=[name].[ext]!./images/icon-72x72.png'; import '!file-loader?name=[name].[ext]!./images/icon-96x96.png'; import '!file-loader?name=[name].[ext]!./images/icon-120x120.png'; import '!file-loader?name=[name].[ext]!./images/icon-128x128.png'; import '!file-loader?name=[name].[ext]!./images/icon-144x144.png'; import '!file-loader?name=[name].[ext]!./images/icon-152x152.png'; import '!file-loader?name=[name].[ext]!./images/icon-167x167.png'; import '!file-loader?name=[name].[ext]!./images/icon-180x180.png'; import '!file-loader?name=[name].[ext]!./images/icon-192x192.png'; import '!file-loader?name=[name].[ext]!./images/icon-384x384.png'; import '!file-loader?name=[name].[ext]!./images/icon-512x512.png'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/extensions /* eslint-enable import/no-webpack-loader-syntax */ import configureStore from './configureStore'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import './global-styles'; // Observe loading of Open Sans (to remove open sans, remove the <link> tag in // the index.html file and this observer) const openSansObserver = new FontFaceObserver('Open Sans', {}); // When Open Sans is loaded, add a font-family using Open Sans to the body openSansObserver.load().then(() => { document.body.classList.add('fontLoaded'); }, () => { document.body.classList.remove('fontLoaded'); }); // Create redux store with history const initialState = {}; const history = createHistory(); const store = configureStore(initialState, history); const MOUNT_NODE = document.getElementById('app'); const render = (messages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={messages}> <ConnectedRouter history={history}> <App /> </ConnectedRouter> </LanguageProvider> </Provider>, MOUNT_NODE ); }; if (module.hot) { // Hot reloadable React components and translation json files // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept(['./i18n', 'containers/App'], () => { ReactDOM.unmountComponentAtNode(MOUNT_NODE); render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(import('intl')); })) .then(() => Promise.all([ import('intl/locale-data/jsonp/en.js'), import('intl/locale-data/jsonp/de.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require } Most of the code is almost untouched after cloning it from react-boiler-plate, only changed index.js to just have the form and modified reducer.js as well. I can see from redux dev tools that I have the form keys: but the error message I get is and the app won't load: Thanks a MILLION in advance! A: Finally figured this out. Because I was using immutableJS, all I had to do was change the import from: import { Form, Control } from 'react-redux-form'; to: import { Form, Control } from 'react-redux-form/immutable';
{ "pile_set_name": "StackExchange" }
Q: how can signing/encryption of token based authentication work for a stateless server (REST) I have clients which are all browsers. All clients render just a single page application getting data from a Web API. The design of the API follows REST principles. This is my authentication flow: I use basic authentication over SSL for my login view. If the user`s sent username and password are valid I put a token string into the response This token is stored in the local storage on client side Each further request to a ressource endpoint of the server API includes the token. Before I do further investigation with the token like checking its expiration date: I need to know wether the authenticity of the token is still valid or someone has modified it. This assumes that the token was signed with a key before. OR I need to decrypt the encrypted token. Question 1) Do steps 6 and 7 make sense using SSL ? Question 2) Lets assume steps 6 and 7 make sense then I would have done the following: When the for example json web token (JWT) after successful login is created I sign it with a key. This key is somewhere on the server stored maybe in an xml file or in a singleton class. Wherever I store this sign key when I create the token I have to use the same key to validate the token. The same is valid for the encryption of the token. How is it possible to use different sign keys for a token maybe on a user basis. That means each authenticated login gets a token with an individual sign key. The next time the user is requesting a resource endpoint I want to know whether the token has still the authenticity. But I can check this only with the same sign key the token was created with. Question 3) Where should this sign key be stored ? A: If you use JWT you have different possibilities of security: Sign the token (see JWS). In this case a man-in-the-middle can still read the contents of this token but cannot modify it because he doesn't have the key to sign it and when the server checks the authenticity of the token it will detect that it has been tampered with Encrypt the token (see JWE). In this case a man-in-the middle cannot read the contents of the token, nor he can modify its contents. Using SSL in your case would ensure that the token cannot be stolen by man-in-the-middles. So unless you have some super secret information stored inside this token, signing it should be sufficient. Obviously the signing key should be stored on the server only and not shared with the rest of the world. As far as your question about signing the token with different keys depending on the user is concerned, I don't think this is necessary. Personally I would use a JWT token which contains only a minimum information like the exp and jti claims and sign it with a secret key. Then I would use the value of this token as key in a key/value store on the server (could be some cache implementation like memcached or NoSQL DB) and would associate the username and any other necessary information to this token. The value will be cached for the duration of validity of the token. When the client sends the JWT token to the server, the server would validate the signature of the token to ensure that its value hasn't been tampered with and then look it the cache for the associated user information.
{ "pile_set_name": "StackExchange" }
Q: Watershed segmentation algorithms cannot work correctly in opencv android Watershed segmentation algorithms cannot work in opencv android. I already used Watershed segmentation algorithms in c++ and java. But in android opencv it gives me error. I don't know why? I know Watershed segmentation algorithms takes 2 parameters of Mat typed object one is 8-bit 3 channel image and other one is 32-bit single channel image. But its gives me wrong parameter error. A: The first step is to double-check each Mat has the type you think it does by using the myMat.depth() and myMat.channels() functions. The function watershed uses two Mat arguments. The first should be an 8-bit, 3-channel image, and the second should be a 32-bit single-channel image. If they are not the right kind of image, use cvtColor to convert from what you have to what you need.
{ "pile_set_name": "StackExchange" }
Q: Smallest square in which other squares fit What is the sidelength of the smallest square in which one can fit $n$ non-overlapping squares of sidelengths $1,2,3,4,...,n$ ? And what is the sidelength of the smallest cube in which one can fit $n$ non-intersecting cubes of sidelengths $1,2,3,4,...,n$ ? All squares/cubes have all sides paralell, no rotation A: For 180 dollars, you can get a 37 squares solution and there is some discussion of cubes and here's a discussion of 70 squares.
{ "pile_set_name": "StackExchange" }
Q: Removing duplication (with Applicative ((->) t), perhaps?) I was playing around with a simple function for someone else's Stack Overflow question, and wrote the expression: f a x ++ f a y Obviously this is the best way to write that expression in real life, given I have all those variables in scope anyway, but I saw the duplication of f a, and thought "Hey, maybe you can remove that with the Applicative instance for functions". I wound up with: liftA2 (++) (flip f x) (flip f y) a which is just awful. Is there some nicer way to remove this duplication?Obviously I could also remove the duplication by binding f a to something in a where clause, but this was intended as an exercise in using built-in functions. A: You could do ((++) `on` f a) x y That doesn't use Applicative, though (sorry). A: [...] maybe you can remove that with the Applicative instance for functions. Do you have to use the Applicative instance of ((->) t)? If you just want to get rid of the duplicated f a, why not use the list monad, instead? [x, y] >>= f a or, equivalently, f a =<< [x, y] Example: λ> let f :: Int -> Int -> [Int]; f a x = [a .. x] λ> f 1 2 ++ f 1 3 [1,2,1,2,3] λ> [2, 3] >>= f 1 [1,2,1,2,3] λ> f 1 =<< [2, 3] [1,2,1,2,3] A: Bikeshedding is fun! Another option would be to use the Monoid instance for functions: (($x) <> ($y)) (f a)
{ "pile_set_name": "StackExchange" }
Q: How to output logs to a JTextArea using Log4j2 I have been trying to output logs to a JTextArea for days and still no luck. Basically what I have tried is creating my own custom appender following existing appender like consoleAppender and tried to configure it in log4j2.xml. I feel I am heading the right direction but somehow I couldn't get it to work. I have asked in log4j2 user mailing list and no one seems to care to help me. Hopefully I can get my help here. If you know how to achieve it, please give me steps or even code snippets. Thank you for your help in advanced. Okay, since someone down voted my question as it doesn't show any effort then I'd better show some. I didn't show anything I have done was because I am not so sure what I was doing was the correct way and people might have their own approach. the problems I am facing are, I cannot find a way to pass that JTextArea object to my TextAreaAppender When I tried to run the test classes, always getting an error saying TextAreaAppender CLASS_NOT_FOUND, but I have tried all the possible way I can find to specify the class attribute in log4j2.xml codes are as following, TextAreaAppender public class TextAreaAppender extends AbstractOutputStreamAppender<OutputStreamManager>{ private static TextAreaManagerFactory factory = new TextAreaManagerFactory(); public enum Target { TEXTAREA } protected TextAreaAppender(String name, Layout<? extends Serializable> layout, Filter filter, OutputStreamManager manager, boolean ignoreExceptions) { super(name, layout, filter, ignoreExceptions, true, manager); // TODO Auto-generated constructor stub } @PluginFactory public static TextAreaAppender createAppender( @PluginElement("Layout") Layout<? extends Serializable> layout, @PluginElement("Filters") final Filter filter, @PluginAttribute("target") final String t, @PluginAttribute("name") final String name, @PluginAttribute("follow") final String follow, @PluginAttribute("ignoreExceptions") final String ignore) { if (name == null) { LOGGER.error("No name provided for TextAreaAppender"); return null; } if (layout == null) { layout = PatternLayout.createLayout(null, null, null, null, null, null); } final boolean isFollow = Boolean.parseBoolean(follow); final boolean ignoreExceptions = Booleans.parseBoolean(ignore, true); final Target target = t == null ? Target.TEXTAREA : Target.valueOf(t); return new TextAreaAppender(name, layout, filter, getManager(isFollow, target, layout), ignoreExceptions); } private static OutputStreamManager getManager(final boolean follow, final Target target, final Layout<? extends Serializable> layout) { final String type = target.name(); //should change to getOutputStream(JTextArea), //but not sure how I can pass textarea object to this class final OutputStream os = getOutputStream(follow, target); return OutputStreamManager.getManager(target.name() + "." + follow, new FactoryData(os, type, layout), factory); } private static OutputStream getOutputStream(JTextArea ta){ return new TextAreaOutputStream(ta); } private static class TextAreaOutputStream extends OutputStream { private final JTextArea output; public TextAreaOutputStream(JTextArea ta){ this.output = ta; } @Override public void write(int i) throws IOException{ output.append(String.valueOf((char) i)); } } /** * Data to pass to factory method. */ private static class FactoryData { private final OutputStream os; private final String type; private final Layout<? extends Serializable> layout; /** * Constructor. * @param os The OutputStream. * @param type The name of the target. * @param layout A Serializable layout */ public FactoryData(final OutputStream os, final String type, final Layout<? extends Serializable> layout) { this.os = os; this.type = type; this.layout = layout; } } /** * Factory to create the Appender. */ private static class TextAreaManagerFactory implements ManagerFactory<OutputStreamManager, FactoryData> { /** * Create an OutputStreamManager. * @param name The name of the entity to manage. * @param data The data required to create the entity. * @return The OutputStreamManager */ @Override public OutputStreamManager createManager(final String name, final FactoryData data) { return new TextAreaOutputStreamManager(data.os, data.type, data.layout);// protected constructor??? } } private static class TextAreaOutputStreamManager extends OutputStreamManager{ public TextAreaOutputStreamManager(OutputStream os, String name, Layout<?> layout) { super(os, name, layout); // TODO Auto-generated constructor stub } } } UI test class public class Log4j2Example { class LogModel extends AbstractTableModel{ @Override public int getColumnCount() { // TODO Auto-generated method stub return 1; } @Override public int getRowCount() { // TODO Auto-generated method stub return 0; } @Override public Object getValueAt(int rowIndex, int columnIndex) { // TODO Auto-generated method stub switch(columnIndex){ case 0: return null; default: return null; } } } private final static JTextArea textarea = new JTextArea(); private final LogModel model = new LogModel(); private final JTable table = new JTable(model); static Log4j2Example INSTANCE = new Log4j2Example(); JFrame frame = new JFrame(); void run(){ frame.setLayout(new BorderLayout()); table.setBorder(new TitledBorder("Table")); textarea.setBorder(new TitledBorder("Text Area")); textarea.setPreferredSize(new Dimension(100, 150)); textarea.setEditable(false); frame.add(table); frame.add(textarea, BorderLayout.SOUTH); frame.setVisible(true); frame.setSize(400, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } static final Logger logger = LogManager.getLogger(Log4j2Example.class.getName()); public static void main(String[] args) { INSTANCE.run(); System.out.println("test"); logger.trace("Entering Log4j Example."); Hello hello = new Hello(); if (!hello.callMe()) { logger.error("Ohh!Failed!"); } logger.trace("Exiting Log4j Example."); } } log4j2.xml <?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Appenders> <Console name="CONSOLE" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> </Console> <TextArea name="TextArea" class="testing.Log4j2Example.TextAreaAppender"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> </TextArea> </Appenders> <Loggers> <Logger name="testing.Log4j2Example" level="ALL"> <AppenderRef ref="TextArea"/> </Logger> <Root level="ERROR"> <AppenderRef ref="CONSOLE"/> </Root> </Loggers> </Configuration> A: The following approach worked for me, which I have based on the log4j solution presented here with additional general information on log4j2 appenders here. JTextAreaAppender.java import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttribute; import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.config.plugins.PluginFactory; import javax.swing.*; import java.util.ArrayList; import static javax.swing.SwingUtilities.invokeLater; import static org.apache.logging.log4j.core.config.Property.EMPTY_ARRAY; import static org.apache.logging.log4j.core.layout.PatternLayout.createDefaultLayout; @Plugin(name = "JTextAreaAppender", category = "Core", elementType = "appender", printObject = true) public class JTextAreaAppender extends AbstractAppender { private static volatile ArrayList<JTextArea> textAreas = new ArrayList<>(); private int maxLines; private JTextAreaAppender(String name, Layout<?> layout, Filter filter, int maxLines, boolean ignoreExceptions) { super(name, filter, layout, ignoreExceptions, EMPTY_ARRAY); this.maxLines = maxLines; } @SuppressWarnings("unused") @PluginFactory public static JTextAreaAppender createAppender(@PluginAttribute("name") String name, @PluginAttribute("maxLines") int maxLines, @PluginAttribute("ignoreExceptions") boolean ignoreExceptions, @PluginElement("Layout") Layout<?> layout, @PluginElement("Filters") Filter filter) { if (name == null) { LOGGER.error("No name provided for JTextAreaAppender"); return null; } if (layout == null) { layout = createDefaultLayout(); } return new JTextAreaAppender(name, layout, filter, maxLines, ignoreExceptions); } // Add the target JTextArea to be populated and updated by the logging information. public static void addLog4j2TextAreaAppender(final JTextArea textArea) { JTextAreaAppender.textAreas.add(textArea); } @Override public void append(LogEvent event) { String message = new String(this.getLayout().toByteArray(event)); // Append formatted message to text area using the Thread. try { invokeLater(() -> { for (JTextArea textArea : textAreas) { try { if (textArea != null) { if (textArea.getText().length() == 0) { textArea.setText(message); } else { textArea.append("\n" + message); if (maxLines > 0 & textArea.getLineCount() > maxLines + 1) { int endIdx = textArea.getDocument().getText(0, textArea.getDocument().getLength()).indexOf("\n"); textArea.getDocument().remove(0, endIdx + 1); } } String content = textArea.getText(); textArea.setText(content.substring(0, content.length() - 1)); } } catch (Throwable throwable) { throwable.printStackTrace(); } } }); } catch (IllegalStateException exception) { exception.printStackTrace(); } } } log4j2.xml <?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN" packages=""> <Properties> <Property name="log-path">log</Property> </Properties> <Appenders> <Console name="console-log" target="SYSTEM_OUT"> <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"/> </Console> <JTextAreaAppender name="jtextarea-log" maxLines="100"> <PatternLayout> <pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss} %msg%n</pattern> </PatternLayout> </JTextAreaAppender> </Appenders> <Loggers> <Logger name="My Logger" level="debug" additivity="false"> <appender-ref ref="console-log" level="debug"/> <appender-ref ref="jtextarea-log" level="debug"/> </Logger> <Root level="info" additivity="false"> <AppenderRef ref="console-log"/> </Root> </Loggers> </Configuration> Add the following lines to your application code, where your GUI is defined, in this example added to the constructor of the class MyClass: protected static Logger logger; public MyClass() { // Setup logger logger = LogManager.getLogger("My Logger"); ... // Create logging panel JTextArea jLoggingConsole = new JTextArea(5,0); // 5 lines high here jLoggingConsole.setLineWrap(true); jLoggingConsole.setWrapStyleWord(true); jLoggingConsole.setEditable (false); jLoggingConsole.setFont(new Font("Courier", Font.PLAIN, 12)); // Make scrollable console pane JScrollPane jConsoleScroll = new JScrollPane(this.jLoggingConsole); jConsoleScroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS ); // Subscribe the text area to JTextAreaAppender JTextAreaAppender.addLog4j2TextAreaAppender(this.jLoggingConsole); ... }
{ "pile_set_name": "StackExchange" }
Q: Start timer after playing sound file and avoid locking GUI I'm trying to make a GUI that first plays a sound file after clicking a button and after playing it, it starts a timer. Now the easiest way I found to get this behaviour is to play the sound file synchronously inside the GUI. This way the GUI 'Blocks' and only starts the timer after the sound file has finished playing. Here is the problem: I didn't anticipate the sound file to be this long but some are quite lengthy and cause the GUI to display 'Program not responding'. Now what can I do to still start the timer after playing the sound but not getting the GUI locked? I was thinking of using a Task but checking whether the task is completed will still probably lock the GUI. What can I do to make this work? UPDATE: This code runs in an other Thread, to get the timer started in the GUI the following code is used (using the solution provided by Marc Gravell found here) //start timer after playing sound source: this.Invoke((MethodInvoker)delegate { if (!timer.Enabled) timer.Start(); }); A: Very simple task using threads.Here is an example how you can accomplish this: private void button1_Click(object sender, EventArgs e) { new System.Threading.Thread(testMethod).Start(); //starting a new thread } public void testMethod() //method will play sound and start timer after that { System.Media.SoundPlayer sp = new System.Media.SoundPlayer(filepath); sp.Play(); timer1.Start(); }
{ "pile_set_name": "StackExchange" }
Q: Existe IDE para desenvolver interface grafica GTK? Quero desenvolver programas com interface para o Linux. Minha dúvida é a seguinte: Existe IDE para desenvolver interface gráfica em GTK no mesmo estilo do Visual Studio da Microsoft? O estilo que me refiro é o "arrasta e solta" utilizado para criar interface quando programado em VB. A: O GTK já tem o Glade. Normalmente recomenda-se o Anjuta. Pode-se usar o Eclipse. O Code::Blocks tem alguma coisa.
{ "pile_set_name": "StackExchange" }
Q: Passing String^ to sql command I'm working on c++/cli window form I want to get string from textBox and bring them to be part of sql command ( I use mysql.h ) but I can't combine this string with normal string. And I try to make String^ as sql command but it can't pass String^ to query function. A: the string^ is a .net string type and must be converted to a native string. Look at this question for the answer.
{ "pile_set_name": "StackExchange" }
Q: Material UI Menu using routes I am toying with material-ui. I implemented LeftNav using routes, but I could not find a way to get IconMenu, or Menu working with links or routes. Anyone can point me to a good source / tutorial? The documentation falls short, and both components seem not to support 'menuItems' as property as LeftNav does. A: another long overdue update: containerElement prop is not supported anymore, use component prop instead. Check out the document here. 2016 December Edit: the linkButton prop is deprecated, you will get a warning: Warning: Unknown props `linkButton` on <a> tag. So simply remove the prop: <MenuItem containerElement={<Link to="/profile" />} primaryText="Profile" leftIcon={ <FontIcon className="material-icons">people</FontIcon> } /> Here's an Example Repo, and the Live Demo Here. Original answer: Just wanted to point out that if you're using react-router, you might want to use <Link to="/some/page" /> rather than the <a> tag. To do this, you need to use the containerElement prop <MenuItem linkButton containerElement={<Link to="/profile" />} primaryText="Profile" leftIcon={ <FontIcon className="material-icons">people</FontIcon> } /> (the ={true} can be omitted if you're only passing true, in other words, <MenuItem linkButton /> is same as <MenuItem linkButton={true} />) The containerElement and linkButton props is actually documented in the buttons section, but you can use it in MenuItem as well. A: Starting with Material-UI 1.0, the new syntax is: <MenuItem component={Link} // the 'to' prop (and any other props not recognized by MenuItem itself) // will be passed down to the Link component to="/profile" > Profile </MenuItem> (Note: this example doesn't include an icon. There is a new ListItemIcon component for that.) A: You can set the linkButtton prop on MenuItem to generate a link, then also add an href. <MenuItem linkButton={true} href="link/to/some/page" primaryText="Sample Link" />
{ "pile_set_name": "StackExchange" }
Q: Getting A Route Parameter for Resolve I'm getting killed by my inability to grok Angular-UI UI-Router. I have a state defined as follows: $stateProvider .state('member', { url: '/member/:membersId', templateUrl: 'templates/member.html', resolve : { // From examples for testing simpleObj: function(){ return {value: 'simple!'}; }, memberDetails : function(FamilyService,$state) { return FamilyService.getMember($state.current.params.membersId); } }, controller: 'MemberController' }); Since the docs say $stateParams aren't available, I'm using $state.current.params. Should be fine. Instead, I get dead air. I can't access the membersId to save my life. To test my service and make sure it's not the problem, I hard coded in a membersId and the controller gets the memberDetails result as well as the simpleObj result. So, Service and Controller and working great. Example of that hardcoded: $stateProvider .state('member', { url: '/member/:membersId', templateUrl: 'templates/member.html', resolve : { // From examples for testing simpleObj: function(){ return {value: 'simple!'}; }, memberDetails : function(FamilyService,$state) { return FamilyService.getMember('52d1ebb1de46c3f103000002'); } }, controller: 'MemberController' }); Even though the docs say you can't use $stateParams in a resolve, I've tried it anyway. It doesn't work either. return FamilyService.getMember($stateParams.membersId); How in the world do I get the membersId param to get passed into the FamilyService for the resolve? I don't have much hair left to pull out; so, someone save me please. A: I finally figured this out. It was quite simple and in the docs. Despite reading several times, I overlooked it each time. I needed to inject $stateParams into the resolve: $stateProvider .state('member', { url: '/member/:membersId', templateUrl: 'templates/member.html', resolve : { simpleObj: function(){ return {value: 'simple!'}; }, memberDetails : function(FamilyService,$stateParams) { return FamilyService.getMember($stateParams.membersId); } }, controller: 'MemberController' }); I still don't understand why the documentation says this is not possible. Two Important $stateParams Gotchas The $stateParams object is only populated after the state is activated and all dependencies are resolved. This means you won't have access to it in state resolve functions. Use $state.current.params instead. $stateProvider.state('contacts.detail', { resolve: { someResolve: function($state){ //* We cannot use $stateParams here, the service is not ready // // Use $state.current.params instead *// return $state.current.params.contactId + "!" }; }, // ... })
{ "pile_set_name": "StackExchange" }
Q: How to make the corners of my border image rounder in kivy self.kk = Button(text='pushme', size_hint=(0.15,0.15), background_color =[0,0,0,1]) self.add_widget(self.kk) with self.kk.canvas.before: BorderImage( size=(self.kk.width + 20 , self.kk.height-7 ), pos=(self.kk.x , self.kk.y), border=(50, 50, 50, 50), source='plain-white-background.jpg') I want to make the border image rounder so i added 'border' as I though this would work i increased and decreased the number but no difference, if possible could give me the answer in python language A: I don't think there's any straightforward way to round the corners of a BorderImage, except by rounding the corners of the image it is displaying. That should actually be quite easy, so it's the most obvious option. Within Kivy, you can use a RoundedRectangle canvas instruction, but then you can't use the normal button background properties (or must manually bind them to control the shape of that new instruction).
{ "pile_set_name": "StackExchange" }
Q: Python Pandas data aggregation by time interval I've got a problem that I can't solve in Python (I've previously done this in SQL and I'm not quite as good at Python as I am at SQL) This is an example of my data: desc date_1 date_2 date_3 values 54287171 cc-cc 2018-03-14 2017-07-03 2018-05-21 55 49410141 other-dd 2012-01-18 2017-01-26 2011-12-30 17 37694577 other-dd 2018-07-05 2017-07-25 2018-06-19 9 54051782 other-cc 2014-10-23 2017-11-24 2014-10-31 37 7378464 dd-cc 2016-08-05 2018-05-15 2016-07-22 92 29665541 dd-cc 2011-12-14 2017-08-01 2012-05-01 40 2999878 dd-cc 2018-10-03 2018-04-13 2018-09-17 37 39453869 cc-cc 2015-11-24 2017-09-09 2015-11-21 81 7181109 dd-dd 2018-01-18 2017-11-24 2018-01-15 27 29580865 dd-cc 2017-04-24 2017-09-07 2017-05-04 38 14778957 other-cc 2017-11-02 2017-06-20 2018-06-26 49 32500886 cc-dd 2017-01-12 2017-05-26 2017-01-12 50 52146154 other-cc 2018-08-01 2017-03-27 2018-07-16 5 7208584 cc-dd 2018-03-13 2018-07-04 2018-04-26 8 35894666 cc-cc 2017-12-04 2018-06-13 2018-08-14 88 27565108 other-other 2015-10-19 2017-03-14 2016-01-22 88 50705834 other-cc 2018-01-08 2017-12-09 2018-01-11 62 45420360 dd-cc 2017-10-23 2017-09-02 2018-01-29 52 55933497 dd-cc 2017-04-14 2018-06-07 2017-09-27 36 46160680 dd-cc 2014-06-05 2018-01-16 2016-01-27 87 In brief, I'm trying to recreate is this functionality: SUM(CASE WHEN date_1 <= date_2 - interval '11' month AND date_3 > date_2 - interval '11' month THEN values end) But then also group by the desc column. So I'm trying to develop a logic that will create an interval between dates and sum all of the values within that interval. To give further context, I'm trying to achieve two things: "date_2" is the date of an event happening and I'm trying to sum up the values at that point in time. Is this just achieved with groupby? I'm then trying to add in the interval in monthly increments, i.e. the same function, summing the values but 12 months prior to date_2, then 11 months prior to date_2, then 10 months prior to date_2. An example output should essentially look like this: desc interval values_sum cc-cc at_date 55 cc-dd at_date 17 other-dd at_date 9 cc-cc date_minus_1 37 cc-dd date_minus_1 92 other-dd date_minus_1 40 cc-cc date_minus_2 37 A: Ok, so using the answer below and the assistance from someone at work I've tried a few different options, this is the most succinct solution we've come up with. from dateutil.relativedelta import relativedelta for i in np.arange(-12,12,1): df['Month_' + str(i)] = df.apply(lambda x: x['values'] if (x['date_2'] <= x['date_1'] + relativedelta(months=i)) \ & (x['date_3'] > x['date_2'] + relativedelta(months=i)) else 0, axis=1) Then the final piece was just a simple groupby on two fields, aggregating by sum. i.e. gf.groupby(['field_1','field_2']).sum()
{ "pile_set_name": "StackExchange" }
Q: Rewriting an url for a user-defined domain I'm not entirely sure if this is possible and tried searching but couldn't find the exact answer to my current situation. I'm building a service which should allow users to point their own domain to the service. (they need to point an A record towards my server ip) I'm able to catch the domain using the catch all in apache. So I made a Vhost record for this catch all in httpd.conf. So all not-defined hostnames in apache are pointed towards a certain directory. Now I would like to pass this domain as a parameter to my service. So is it possible to point this.randomdomain.com to www.mywebserviceurl.com/domain/catch/this.randomdomain.com with .htaccess The address bar should keep the url this.randomdomain.com Edit: RewriteEngine On RewriteRule ^(.*)$ http://example.com/blogs/string/$1 [R=301] The above is redirecting but firefox trows an error "The page isn't redirecting properly - Firefox has detected that the server is redirecting the request for this address in a way that will never complete." And the address is changing which I don't want. thanks! A: Exclude that domain from the rule: RewriteCond %{HTTP_HOST} !=example.com RewriteRule ^(.*)$ http://example.com/blogs/string/$1 [R=301] And if you want the domain too: RewriteCond %{HTTP_HOST} !=example.com RewriteRule ^(.*)$ http://example.com/blogs/string/%{HTTP_HOST}/$1 [R=301]
{ "pile_set_name": "StackExchange" }
Q: Wrong Planet, What would an Aspergers' planet be like? Being on the autism spectrum is often described as a feeling of being on "The Wrong Planet" So I'm wondering what the right planet might be like... For those that are unfamiliar: Social conventions aren't always obvious to the average person with Aspergers' Non-verbal communication is often difficult. (Making eye contact and recognizing facial expressions) Stimming is common. Sensory issues are also somewhat common. (sensitivity to lights, sounds, textures) There's some evidence of trouble with theory of mind Highly specialized areas of interest are a key feature. In my Completely Fictitious Scenario*, people with Aspergers' are an evolutionary result of over-specialization and are so good at specializing they eventually inherit the Earth. What would this society look like? How would things function? *(I really can't stress the fictitious part enough, way too many false theories on autism go mainstream...) A: As someone who also has Aspergers, and comes from a family of aspies, I can state with some certainty that aspies tend to pick a subject of interest, stick with it and become very good at it. That subject could be almost anything other than idle social interaction. My father is undiagnosed, but we have no doubt that he's an aspie, and his area of interest is gardening, specifically orchids, but any gardening interests him, so farming interests is not beyond the bounds of possibility. So, we'd have a society of specialists. They'd probably achieve more than the neurotypicals ever did, as they would be driven by their obsessions, rather than wasting so much time engaging in frivolous chit chat. Conversations would be more goal-oriented - Aspies tend to like talking about their area of specialty, just not meaningless trivialities. After quite some time in an aspie world, I predict that language will become more precise. Aspies tend to be quite pedantic, and can have a hard time accepting misspoken or ambiguous statements even when they know what the speaker should mean. If Aspies inherit our world, then I predict that much communication would be via impersonal means such as texting or email, then telephone, and the last preference would be for face-to-face, except with friends and family. Don't expect much telemarketing any more - an aspie would hate to cold-call someone, and if called by a telemarketer, would typically just hang up or say something rude. Any advertising would tend to appeal more to logic than emotion than is the case now. You may still get wars; while aspies dislike direct conflict, there is no reason why wars might not be fought by proxy using drones and robots more than by aspies with guns. Why send a man to do a job that a robot can do better? A: Most people can be classified as Extrovert vs introvert. Extroverts tend to be more outgoing, expressive, and capable in the social domains. Most leaders tend to be extroverts...from team leads to management to political leadership. Aspie's are pretty much introverts by definition. They tend to be the thinkers and workers, but struggle when it comes to human relations (for a variety of reasons...usually an inability to comprehend non-verbal queue's, though anxiety in general can come up here). Programmers and researchers tend to be introverts as they can reach highly specialized knowledge but tend not to share it readily. So our Wrong World here is ultimately a world full of dreaming introverts. Stackexchange is actually a haven for Aspie's...English is a pretty exacting language and it's hard to interpret the same words in multiple ways (unlike human body language that can be interpreted in any number of ways). It's from behind a computer screen, which tends to negate the feelings of 'being judged' and allows the anxieties to play out in a personal space where they can be managed. If I may speculate...I can see the internet social domain expanding heavily and starting to function at a governing level. Websites where people can post idea's, comments, answers, etc...and have the discussions on a non-personal and exacting level (Having multiple meanings to one thing and not being able to determine which of those meanings is correct can be a source of anxiety, so expect highly specific wording to avoid any of that). Arguments and conflicts still happen, but it tends to be relegated to the comfort of anonymous internet discussion. The problem with this society is it becomes incredibly reliant on each other...no specialist can really exist without having a wide array of others to depend on. So you have people incredibly reliant with each other and the preference not to directly communicate with each other. If this highly specialized setup is disturbed, it tends to collapse with little ability to stop the fall. The other issue that comes out here...the information industry is well suited to an Aspie. Horticulture (read that as gardening) and small scale manufacturing (artisan style) is also very well suited to Aspie's. Mass manufacturing and mass agriculture is not...high accuracy tasks that must be preformed repeatably as industry and farming requires are poorly suited to aspies (boredom and drifting mind issues hit here). You'd likely see a move away from the mass scale industries and more towards small scale 'cottage industry' type setups. Whether or not this can sustain the semi-fragile nature of this society is for more speculation. End note - I'm a diagnosed Aspie. It presents as anxiety that comes up in non-familiar social situations and tends to make me seem quite and a bit withdrawn. I don't mean to offend anyone with this answer and would be interested to hear other peoples takes on it. A: After giving this a bit more thought, I think a "Wrong Planet" would differ quite a bit from person to person... Here's a bit of what my world would be like in no particular order: Nepotism would be a thing of the past Replaced by Meritocracy. The fashion industry, would dramatically shift towards comfortable, functional attire. The tuxedo would be a distant memory. Florescent lighting would be carefully maintained, or replaced with lights that are less likely to flicker or hum. Naming conventions would lean more toward meaningful descriptive titles or sequential numbers. No more silly items on restaurant menus... "Rooty tooty fresh and fruity" would just be: "Pancakes with fruit and whipped cream". "Big Mac" would just be: "Standard Hamburger" or "Basic Hamburger" 1st Street rather than <insert important person> Street. Being efficient would be favored over being friendly in customer service situations. Advertising would be purely informative. "Product X has new feature Y" Full stop. Education would be tailored to the student rather than to an average. Expect a lot more online learning and self-education. "Big Box stores" would largely be replaced by markets filled with independently owned and operated, highly specialized, artisanal shops. Robotics would become a major industry. Most manual labor would be done by robots. The metric system would replace imperial measurement. Except for pints, beer would still come in a proper pint glass. Personal space would be a standard measured distance. People would be expected to ask permission before hugging, shaking hands, etc. with unfamiliar people. Turn signals would have a standard blink rate. News media would change significantly. News organizations that presented opinions as facts would be fined. Not eliminating opinion pieces altogether, but opinion pieces would have to run with a disclaimer. Retractions and corrections would have to receive as much, if not more, airtime or print copy as the original piece being corrected. Most "small talk" would be eliminated. Public transportation would run on time. White collar crime would carry the same sorts of penalties as regular crime. Long rambling lists would become a highly respected poetic form. As a side note, I think a lot of people underestimate the diversity of interests that Aspies engage in. The idea that aspies are only interested in STEM fields (Science, Technology, Engineering and Math) is a misconception. My wife for instance is an amazing sculptor and visual artist.
{ "pile_set_name": "StackExchange" }
Q: sort a jquery div based on one of the (paragraph tags) Following is the repetivite html structure that i have in my template: <div class="mystyle" data-id= "11002"> <div class="style1-header"><h6>Change Status of Task</h6></div> <p class="style1-content">Seriously Change Status of Task</p> <p class="style2-content" style="visibility:hidden">12</p> </div> The above is the html structure that keeps repeating in my html template. I wanted these things to be sorted based on the numbers 12 as in the above case. How can i do it with jquery. The fiddle is available here. A: Use JavaScript's Array.sort method to sort an array of the divs. var $divs = $('div.mystyle').get().sort(function(a,b){ var aKey = +$(a).find('p.style2-content').text(), bKey = +$(b).find('p.style2-content').text(); return aKey - bKey; }); Then append the now sorted array to the DOM. $('body').append($divs);
{ "pile_set_name": "StackExchange" }
Q: I opened my Roth IRA account. Does it makes sense to diversify my initial contribution of $5500? This is my first Roth IRA. I am putting $5500 which is the maximum annual contribution I can make. I was planning to apply the 3 fund portfolio technique by investing this money proportionately in Total US Stock market fund, International Stock market fund and U.S Bond market fund. Does it make sense to diversify to such an extent or I should simply put the money in any 1 index fund and then diversify as and when I put more into the Roth account? A: It varies. Depending on your brokerage, they may charge you per transaction, so the more transactions, the higher the cost. Though this (from what I've seen), is uncommon with many index funds. In terms of how aggressive you want to be with your investment varies on your comfort with risk, timeline of investment and many other factors beyond the scope of this question. The biggest issue you may need to be aware of is if you are looking at mutual funds, they may have minimum investments. Depending on what that minimum investment is set to, you may not be able to split your $5500 into more than one fund. A lot of this comes down to the specific funds in which you are anticipating investing, as well as the service you use to do so (Fidelity, Vanguard, etc). Ultimately, diversification can be a lot safer, but there are logistics to consider. Personally, I began with a target fund (a mutual fund with adjusted risk based on the estimated year of retirement) and add additional mutual funds, stocks and ETFs as time goes on.
{ "pile_set_name": "StackExchange" }