text
stringlengths
64
89.7k
meta
dict
Q: Button click equivalent of pressing the enter key java I have a button with variable name "btntry". When the user clicks this button I want it to perform the same action as would have been performed if the user pressed the enter key. Is this possible? It would be helpful if you could tell me how to insert the code in this case: This are the two methods I have private void btntryActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void entryfieldActionPerformed(java.awt.event.ActionEvent evt) { char[] v = { 'c', 'e', 'n', 't', 'i', 'p', 'e', 'd', 'e' }; char n; n = entryfield.getText().charAt(0); boolean flag = false; int index = 0; boolean flag2 = false; while (index < (v.length)) { if (n == (v[index])) { flag = true; } else { flag = false; } index++; if (flag == true){ flag2 = true; } } if (flag2 == true) { System.out.println("Correct"); } else { System.out.println("Wrong"); } I when the button is clicked I want the same effect as the enter key being pressed A: I when the button is clicked I want the same effect as the enter key being pressed You can make the button the default button for the frame: frame.getRootPane().setDefaultButton( button ); Then when you use the Enter key the ActionListener of the button will be invoked even when the button doesn't have focus.
{ "pile_set_name": "StackExchange" }
Q: Background Image causing memory warning and crash during UITesting I have a simple UITest which taps an item on the tool bar 100 times, running the test with no background image consistently passes, however when I add a background image I receive memory warnings followed by the test failing. I've tried numerous solutions for displaying the image, most all of them cause the same result, memory warnings followed by a crash. I have an image set consisting of three png images sized at 3X: 2304 X 3072, 2X: 1536 X 2048, and 1X: 768 X 1024, as per apple docs. How can I add a background image so that it wont cause memory issues. UITesting Code: func testJustNumberOfRolls() { let app = XCUIApplication() for _ in 1...100 { app.toolbars.buttons["Tip2"].tap() } } ViewController: class TestVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let image = UIImage(named: "feltSized") { self.view.backgroundColor = UIColor(patternImage: image) } } } Test Logs: 11:10:49.317 XCTRunner[6768:2874277] -[TestingUIActual testJustNumberOfRolls] started activity <XCActivityRecord: 0x1314a5ab0> 2015-12-11 17:10:49 +0000: Wait for app to idle 11:10:49.528 XCTRunner[6768:2874277] Waiting for app quiescence... 11:10:49.529 XCTRunner[6768:2874357] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> event loop is idle 1 -> 0 11:10:49.529 XCTRunner[6768:2874357] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> hasReceivedAnimationsHaveFinished 1 -> 0 11:10:49.530 XCTRunner[6768:2874357] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> event loop is idle 1 -> 0 11:10:49.531 XCTRunner[6768:2874357] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> hasReceivedAnimationsHaveFinished 1 -> 0 11:10:49.535 XCTRunner[6768:2874320] Got AX notification 4002 11:10:49.536 XCTRunner[6768:2874320] Got animations reply. 11:10:49.536 XCTRunner[6768:2874320] Animations are not active. 11:10:49.537 XCTRunner[6768:2874320] Got AX notification 4002 11:10:49.537 XCTRunner[6768:2874322] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> hasReceivedAnimationsHaveFinished 0 -> 1 11:10:49.538 XCTRunner[6768:2874320] Got event loop idle reply. 11:10:49.539 XCTRunner[6768:2874320] Event loop is idle. 11:10:49.538 XCTRunner[6768:2874322] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> event loop is idle 0 -> 1 11:10:49.540 XCTRunner[6768:2874322] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> hasReceivedAnimationsHaveFinished 0 -> 1 11:10:49.541 XCTRunner[6768:2874322] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> event loop is idle 0 -> 1 11:10:49.542 XCTRunner[6768:2874277] App has quiesced. 11:10:49.542 XCTRunner[6768:2874277] -[TestingUIActual testJustNumberOfRolls] finished activity <XCActivityRecord: 0x1314a5ab0> 2015-12-11 17:10:49 +0000: Wait for app to idle (0.225394s) 11:10:49.550 XCTRunner[6768:2874277] -[TestingUIActual testJustNumberOfRolls] finished activity <XCActivityRecord: 0x1314a2970> 2015-12-11 17:10:49 +0000: Find the "Tip2" Button (0.298589s) 11:10:49.553 XCTRunner[6768:2874277] -[TestingUIActual testJustNumberOfRolls] started activity <XCActivityRecord: 0x1314abf80> 2015-12-11 17:10:49 +0000: Synthesize event 11:10:49.966 XCTRunner[6768:2874320] Got AX notification 4002 11:10:49.967 XCTRunner[6768:2874320] Got event completion. 11:10:49.969 XCTRunner[6768:2874277] -[TestingUIActual testJustNumberOfRolls] finished activity <XCActivityRecord: 0x1314abf80> 2015-12-11 17:10:49 +0000: Synthesize event (0.416638s) 11:10:49.973 XCTRunner[6768:2874320] Got AX notification 4002 11:10:49.988 XCTRunner[6768:2874277] -[TestingUIActual testJustNumberOfRolls] started activity <XCActivityRecord: 0x1315415e0> 2015-12-11 17:10:49 +0000: Wait for app to idle 11:10:50.197 XCTRunner[6768:2874277] Waiting for app quiescence... 11:10:50.198 XCTRunner[6768:2874358] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> event loop is idle 1 -> 0 11:10:50.198 XCTRunner[6768:2874358] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> hasReceivedAnimationsHaveFinished 1 -> 0 11:10:50.199 XCTRunner[6768:2874358] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> event loop is idle 1 -> 0 11:10:50.200 XCTRunner[6768:2874358] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> hasReceivedAnimationsHaveFinished 1 -> 0 11:10:50.204 XCTRunner[6768:2874358] Got AX notification 4002 11:10:50.204 XCTRunner[6768:2874358] Got event loop idle reply. 11:10:50.205 XCTRunner[6768:2874358] Event loop is idle. 11:10:50.205 XCTRunner[6768:2874567] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> hasReceivedAnimationsHaveFinished 0 -> 1 11:10:50.206 XCTRunner[6768:2874567] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> event loop is idle 0 -> 1 11:10:50.437 XCTRunner[6768:2874358] Got AX notification 4002 11:10:50.438 XCTRunner[6768:2874358] Got animations reply. 11:10:50.442 XCTRunner[6768:2874358] Animations are not active. 11:10:50.443 XCTRunner[6768:2874567] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> hasReceivedAnimationsHaveFinished 0 -> 1 11:10:50.444 XCTRunner[6768:2874567] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> event loop is idle 0 -> 1 11:10:50.446 XCTRunner[6768:2874277] App has quiesced. 11:10:50.447 XCTRunner[6768:2874277] -[TestingUIActual testJustNumberOfRolls] finished activity <XCActivityRecord: 0x1315415e0> 2015-12-11 17:10:49 +0000: Wait for app to idle (0.459272s) 11:10:50.460 XCTRunner[6768:2874277] -[TestingUIActual testJustNumberOfRolls] finished activity <XCActivityRecord: 0x13149e5f0> 2015-12-11 17:10:49 +0000: Tap "Tip2" Button (1.4335s) 11:10:50.464 XCTRunner[6768:2874277] -[TestingUIActual testJustNumberOfRolls] started activity <XCActivityRecord: 0x1314af0f0> 2015-12-11 17:10:50 +0000: Tap "Tip2" Button 11:10:50.466 XCTRunner[6768:2874277] -[TestingUIActual testJustNumberOfRolls] started activity <XCActivityRecord: 0x131544810> 2015-12-11 17:10:50 +0000: Wait for app to idle 11:10:50.669 XCTRunner[6768:2874277] Waiting for app quiescence... 11:10:50.669 XCTRunner[6768:2874567] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> event loop is idle 1 -> 0 11:10:50.670 XCTRunner[6768:2874567] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> hasReceivedAnimationsHaveFinished 1 -> 0 11:10:50.670 XCTRunner[6768:2874567] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> event loop is idle 1 -> 0 11:10:50.671 XCTRunner[6768:2874567] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> hasReceivedAnimationsHaveFinished 1 -> 0 11:10:50.676 XCTRunner[6768:2874356] Got AX notification 4002 11:10:50.676 XCTRunner[6768:2874356] Got animations reply. 11:10:50.677 XCTRunner[6768:2874356] Animations are not active. 11:10:50.677 XCTRunner[6768:2874567] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> hasReceivedAnimationsHaveFinished 0 -> 1 11:10:50.677 XCTRunner[6768:2874567] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> event loop is idle 0 -> 1 11:10:50.679 XCTRunner[6768:2874320] Got AX notification 4002 11:10:50.679 XCTRunner[6768:2874320] Got event loop idle reply. 11:10:50.680 XCTRunner[6768:2874320] Event loop is idle. 11:10:50.680 XCTRunner[6768:2874357] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> hasReceivedAnimationsHaveFinished 0 -> 1 11:10:50.681 XCTRunner[6768:2874357] <XCUIApplicationProcess: 0x12fe466a0 mikepland.crapsBuzzInSwift (6775)> event loop is idle 0 -> 1 11:10:50.682 XCTRunner[6768:2874277] App has quiesced. 11:10:50.682 XCTRunner[6768:2874277] -[TestingUIActual testJustNumberOfRolls] finished activity <XCActivityRecord: 0x131544810> 2015-12-11 17:10:50 +0000: Wait for app to idle (0.216641s) 11:10:50.718 Xcode[1265:207640] Test operation failure: Lost connection to test manager service. 11:10:50.719 Xcode[1265:207640] _finishWithError:Error Domain=IDETestOperationsObserverErrorDomain Code=4 "Lost connection to test manager service." UserInfo={NSLocalizedDescription=Lost connection to test manager service.} didCancel: 1 A: UPDATE: I tried not displaying ANY images, this seems to be better. Error shows up at 'lost connection to test manager services'. At this point I have refactored my app to avoid long animations to avoid needing a timeout on my tests, then recoded app to hide ALL images and background colors. Even then the error still shows up, although tests are able to run for longer. I was able to replicate on a brand new app with just a background pattern and a button, even that was causing the error if running tests for more than a few minutes, and thats a BRAND NEW APP. So idk what else to do, hopefully this will be fixed soon.
{ "pile_set_name": "StackExchange" }
Q: UICollectionView with autosizing cell (estimatedSize) and sectionHeadersPinToVisibleBounds goes mental Consider the following situation. I have an UICollectionView (inside UICollectionViewController), which looks almost the same as UITableView (the reason why I don't use UITalbeView is because I have non data views on layout, that I don't want to manage and mess with my IndexPath). In order to achieve the autosizing cells I've set estimatedItemSize, something like that: layout.estimatedItemSize = CGSize(width: self.view.bounds.size.width, height: 72) Also, in my cell I have layout attributes: override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { layoutAttributes.bounds.size.height = systemLayoutSizeFitting(UILayoutFittingCompressedSize).height return layoutAttributes } So, by doing that I've got exact layout as UITableView with autosizing. And it works perfectly. Now, I am trying to add the header and pin it on scrolling to the top of the section, like that: layout.sectionHeadersPinToVisibleBounds = false but layout goes into weird state, I have glitches all over the place, cells overlapping each other, and headers sometimes doesn't stick. UPDATE: The code of view controller and cell: class ViewController: UICollectionViewController { override func viewDidLoad() { super.viewDidLoad() let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout layout.sectionHeadersPinToVisibleBounds = true layout.estimatedItemSize = CGSize(width: collectionView?.bounds.size.width ?? 0, height: 36) // enables dynamic height } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 10 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell cell.heightConstraint.constant = CGFloat(indexPath.row * 10 % 100) + 10 // Random constraint to make dynamic height work return cell } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { return collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) } class CustomCell : UICollectionViewCell { let identifier = "CustomCell" @IBOutlet weak var rectangle: UIView! @IBOutlet weak var heightConstraint: NSLayoutConstraint! override func awakeFromNib() { translatesAutoresizingMaskIntoConstraints = false } override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { layoutAttributes.bounds.size.height = systemLayoutSizeFitting(UILayoutFittingCompressedSize).height return layoutAttributes } Details of lagging in video: https://vimeo.com/203284395 A: Update from WWDC 2017: My colleague was on WWDC 2017, and he asked one of the UIKit engineers about this issue. The engineer confirmed that this issue is known bug by Apple and there is no fix at that moment.
{ "pile_set_name": "StackExchange" }
Q: virtualenvで仮想環境に入れません。 Pythonの初心者です。 Windouws10、Python3.8を使っております。 こちらの記事に従ってDjangoを使おうとしていました。 https://qiita.com/kaki_k/items/1fff7fefcf26dc4b69bc しかし、この記事の 仮想環境を使う 仮想環境 env1 の中に入ってみます。 C:¥Users¥hoge¥Documents> cd env1 C:¥Users¥hoge¥Documents¥env1> Scripts¥activate (env1) C:¥Users¥hoge¥Documents¥env1> このように (env1) と表示されれば成功です。 を実行していたところで問題が起きました。 記事と同じようにコマンドプロンプトに C:¥Users¥(ユーザー名)¥Documents>cd env1 C:¥Users¥(ユーザー名)¥Documents¥env1>Scripts¥activate と入力したのですが、次の通り仮想環境(env1)に切り替わってくれないのです。 C:¥Users¥(ユーザー名)¥Documents>cd env1 C:¥Users¥(ユーザー名)¥Documents¥env1>Scripts¥activate C:¥Users¥(ユーザー名)¥Documents¥env1> どうやったら仮想環境に切り替わってくれるのでしょうか? 以下に関係があるかもしれないと思ったことを書きます。 ・virtualenvはちゃんとインストールできていると思います。 C:¥Users¥(ユーザー名)>virtualenv --version virtualenv 20.0.7 from c:¥users¥(ユーザー名)¥appdata¥local¥programs¥python¥python38¥lib¥site-packages¥virtualenv¥__init__.py ・env1を作った時に表示された結果です。 C:¥Users¥(ユーザー名)¥Documents>virtualenv env1 created virtual environment CPython3.8.1.final.0-64 in 4268ms creator CPython3Windows(dest=C:¥Users¥(ユーザー名)¥Documents¥env1, clear=False, global=False) seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=C:¥Users¥(ユーザー名)¥AppData¥Local¥Temp¥tmph_30tf6l¥seed-app-data¥v1) activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator ・「Scripts¥deactivate」を実行した場合は空行を挟まずに改行されます。 C:¥Users¥(ユーザー名)¥Documents¥env1>Scripts\deactivate C:¥Users¥(ユーザー名)¥Documents¥env1> どうかご回答をよろしくお願い致します。 A: 該当の記事が最新の状況に合わせて更新されていないだけではないでしょうか? 単に、デフォルトのインストールではプロンプト文字列を変更しなくなったのだと思われます。 Scripts\activate実行の前後で環境変数を見較べてみましょう。 activateすると、環境変数に以下の変更が入り、deactivateすると元に戻ります。 環境変数PATHの先頭にC:¥Users¥(ユーザー名)¥Documents¥env1\Scriptsフォルダが追加される 環境変数VIRTUAL_ENVが増えて、仮想環境パスC:¥Users¥(ユーザー名)¥Documents¥env1が設定される 環境変数_OLD_VIRTUAL_PATHが増えて、元の環境変数PATHの内容がコピーされる 環境変数_OLD_VIRTUAL_PROMPTが増えて、元の環境変数PROMPTの内容がコピーされる またactivateの前後で pip list -l を実行してみれば、インストールされているモジュールに違いがあることがわかるでしょう。 上記が確認できていれば、仮想環境には切り替わっているが、プロンプト文字列が変更されていないだけ、と思われます。 プロンプト文字列を変更したいのであれば、Scripts\activate.batの中身を書き換えて、好みの内容にカスタマイズすれば良いでしょう。
{ "pile_set_name": "StackExchange" }
Q: How to force idle workers to take jobs in parallel R? I am new to posting here--I searched and couldn't find an answer to my question. I have run the following R parallelized code (from a blog on parallel computing in R) using the parallel package on two different machines and yet get very different process time results. The first machine is a Lenovo laptop with Windows 8, 8GB RAM, Intel i7, 2 cores/4 logical processors. The second machine is a Dell desktop, Windows 7, 16GB RAM, Intel i7, 4 cores/8 logical processors. The code sometimes runs much slower on the second machine. I believe the reason is that the second machine is not using the worker nodes to complete the task. When I use the function snow.time() from the snow package to check node usage, the first machine is using all available workers to complete the task. However, on the more powerful machine, it never uses the workers--the entire task is handled by the master. Why is the first machine using workers, but the second is not with the exact same code? And how do I 'force' the second machine to use the available workers so that the code is truly parallelized and the processing time is sped up? The answers to these would help me tremendously with other work I am doing. Thanks in advance. The graphs from the function snow.time() are below as well as the code I used: runs <- 1e7 manyruns <- function(n) mean(unlist(lapply(X=1:(runs/4), FUN=onerun))) library(parallel) cores <- 4 cl <- makeCluster(cores) # Send function to workers tobeignored <- clusterEvalQ(cl, { onerun <- function(.){ # Function of no arguments doors <- 1:3 prize.door <- sample(doors, size=1) choice <- sample(doors, size=1) if (choice==prize.door) return(0) else return(1) # Always switch } ; NULL }) # Send runs to the workers tobeignored <- clusterEvalQ(cl, {runs <- 1e7; NULL}) runtime <- snow.time(avg <- mean(unlist(clusterApply(cl=cl, x=rep(runs, 4), fun=manyruns)))) stopCluster(cl) plot(runtime) A: Try clusterApplyLB instead of clusterApply. The "LB" is for load balancing. The non LB version divides the number of tasks between the nodes and sends them in a batch, but if one node finishes early then it sits idle waiting for the others. The LB version sends one task to each node then watches the nodes and when a node finishes it sends another task to that node until all the tasks are assigned. This is more efficient if the time for each task varies widely, but is less efficient if all the tasks will take about the same amount of time. Also check the versions of R and parallel. If I am remembering correctly the clusterApply function used to not do things in parallel on Windows machines (but I don't see that note any more, so that has likely been remedied in recent versions), so the difference could be different versions of the parallel package. The parLapply function did not have the same issue, so you could rewrite your code to use it instead and see if that makes a difference. A: I don't think it's possible to use the snow.timing function from the snow package while getting all of the other functions from the parallel package. The source for parallel in R 3.2.3 has some place holder code for timing, but it doesn't appear to be either complete or compatible with the snow.timing function in snow. I think you'll still get correct results from clusterApply, but the object returned by snow.time will be equivalent to executing: runtime <- snow.time(Sys.sleep(20)) If you want to use snow.timing, I suggest only loading snow, although you can still access functions such as detectCores using the syntax parallel::detectCores(). I don't really know why your script occasionally runs slowly on your desktop machine, but I think that the way you are parallelizing it is reasonable and correct. You might want to try benchmarking manyruns sequentially on both machines in order to rule out any differences in the random number generation code on the two systems. But perhaps the problem was caused by a system service that was slowing down the whole system.
{ "pile_set_name": "StackExchange" }
Q: Is the sentence "I would be going on a vacation." grammatically correct? Is this sentence correct? "I would be going on a vacation." I tried searching for similar sentences online and came across Conditional tenses. But from what I understand they have two clause - the 'if' and the main clause. So if the sentence was, "If I completed my work, I would be going on vacation." it probably would have been correct. But I am unsure if "I would be going on vacation" is correct. A: Yes, but only in a specific context. "Would" is the past tense of the verb will. That would make your sentence incorrect, because "be going" is future tense. However, "would" can also be used to indicate the consequence of an imagined event or situation, so it can be future-looking but only if you include a condition, for example: I would be going on a vacation if only I had a passport. If that isn't your intention, then your sentence is incorrect and you probably mean to say: I will be going on a vacation. or even I am going on a vacation.
{ "pile_set_name": "StackExchange" }
Q: How to add tab in product Edit Page in Magento2? How to add tab in product edit page in magento2? I refering some tutorial ...but its not woking for me... https://webkul.com/blog/add-tab-product-page-magento-admin/ If anyone knows ,Explain me... A: You can add custom tab using UI component app/code/Namespace/Modulename/view/adminhtml/ui_component/product_form.xml <form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"> <fieldset name="demotab"> <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <item name="label" xsi:type="string" translate="true">Demo Tab</item> <item name="collapsible" xsi:type="boolean">true</item> <item name="sortOrder" xsi:type="number">100</item> </item> </argument> <container name="fieldname_container" > <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <item name="sortOrder" xsi:type="number">160</item> </item> </argument> <htmlContent name="html_content_demo"> <argument name="block" xsi:type="object">Namespace\Modulename\Block\Adminhtml\Catalog\Product\Edit\Tab\Demo</argument> </htmlContent> </container> </fieldset> </form> app/code/Namespace/Modulename/Block/Adminhtml/Catalog/Product/Edit/Tab/Demo.php <?php namespace Namespace\Modulename\Block\Adminhtml\Catalog\Product\Edit\Tab; use Magento\Backend\Block\Template\Context; use Magento\Framework\Registry; class Demo extends \Magento\Framework\View\Element\Template { /** * @var string */ protected $_template = 'product/edit/demo.phtml'; /** * Core registry * * @var Registry */ protected $_coreRegistry = null; public function __construct( Context $context, Registry $registry, array $data = [] ) { $this->_coreRegistry = $registry; parent::__construct($context, $data); } /** * Retrieve product * * @return \Magento\Catalog\Model\Product */ public function getProduct() { return $this->_coreRegistry->registry('current_product'); } } app/code/Namespace/Modulename/view/adminhtml/templates/product/edit/demo.phtml <?php echo "This is demo tab content."; ?>
{ "pile_set_name": "StackExchange" }
Q: Travis uses Firefox 56 although Firefox 59 is installed on same system When running Selenium on Travis, it uses Firefox version 56. I need to use the latest version of Firefox, 59. Running apt-get update and upgrade does not solve this problem, but instead leaves the system with two different versions of Firefox, both 56 and 59. $ which firefox /usr/local/bin/firefox $ firefox --version Mozilla Firefox 56.0.2 but $ /usr/bin/firefox --version Mozilla Firefox 59.0.2 Anyone knows how to resolve this so that Firefox 59 is the only version available on the system? One temporary fix could be just to copy over the 56 bin file with the 59 one. A: Java perspective Even though you are having multiple installations of different versions of Firefox Binary you can still pick up your choice of the desired Firefox Binary version through the setBinary() option of FirefoxOptions() Class during your test execution as follows : System.setProperty("god.bless.us", "C:/Utility/BrowserDrivers/geckodriver.exe"); FirefoxOptions options = new FirefoxOptions(); options.setBinary("C:\\Program Files\\Mozilla Firefox\\firefox.exe"); WebDriver driver = new FirefoxDriver(options); driver.get("https://stackoverflow.com"); System.out.println("Page Title is : "+driver.getTitle()); driver.quit();
{ "pile_set_name": "StackExchange" }
Q: Install windows (bootcamp) without CD or USB Flash Drive I'm currently trying to install windows on my macbook (13in, 2011), but without any success. My CD drive is dead (as a matter of facts its ruining any cds I put in it), and I simply cant boot via USB. Im running Mavericks. I've tried enabling USB burning on bootcamp assistant and codesigning it, and it worked for Windows 8, I could even boot, but couldn't install it on the bootcamp partition. As soon as I get to the screen in which to select the partition, windows refuses to install, with some error code. I've also tried formatting this partition as ntfs from inside the windows installer, but it doesn't work also. After I did that, whenever I restart my macbook, I get an error message saying "No bootable device found" or something like that, and I can only get back to OSX by holding option and selecting it manually. After All of that I've tried windows 7, and this time the bootloader (when I hold the option key) doesn't recognize the usb anymore. So, as nothing works, how can I install windows? (It's for gaming purposes). Maybe I can make a small partition, burn the windows installer to it and boot from that? It sounds like a plan, but I cant find how to burn a .iso to a partition anywhere. A: This might seem like a long shot, but it was also the only option for me to install Windows into my Bootcamp partition a little while back. It's also the only option for a Mac that used to have an optical drive but no longer does, since for some reason these devices are no longer able to boot from USB. Use Disk Utility to create a FAT partition a little larger than your wanted Windows partition. Install rEFIt. Reboot twice for rEFIt to install properly. As soon as you see the rEFIt boot menu when starting, it's good. Here you choose the 'Partition Tool', with which you'll change the MBR (Master Boot Record). (On a side note: You can easily uninstall rEFIt by renaming the directory at the root of your harddrive) Install VirtualBox, Parallels or VMware. I did this with VMware back at the time, but all of these should work as long as you're able to mount the virtual harddrive like any removable disk. Use the virtualization software to install Windows into a virtual machine at the size of your wanted partition (not what you made it above, but a little smaller than that). You can of course install from an ISO here, making the state of your disc drive irrelevant. Kill the virtual machine as soon as it reboots the first time after finishing the installation, stopping Windows before being able to configure itself. Use the virtualization software's features to mount the virtual harddrive. Install a tool called WinClone. If your virtual drive is mounted, WinClone should be able to see this in the tab 'Image'. Pull this into an image onto your harddrive. Now choose the 'Restore' tab in WinClone and restore this image to your Bootcamp partition. Now you can reboot and boot into your Bootcamp partition with rEFIt, which is no longer of any use from this point on, but you can keep it around as well. Windows should now continue configuring itself and finish the installation. I stumbled across this solution here in the Apple Support Community and posted about it here a while ago on a German Apple User Forum, if that turns out to be of any use to anybody.
{ "pile_set_name": "StackExchange" }
Q: How to download pdf files in python? I need to download something like str = 'http://query.nytimes.com/mem/archive-free/pdf?res=9A00EEDE1431E13BBC4850DFBF66838A649FDE' url = urllib2.urlopen(str) file = open('test.pdf', 'w') file.write(url.read()) file.close() It just creates a wrong pdf. how do I write that into file? A: You can use the pattern module, which is built on top of urllib2 and has a higher level of abstraction. from pattern.web import URL url = URL('http://query.nytimes.com/mem/archive-free/pdf?res=9A00EEDE1431E13BBC4850DFBF66838A649FDE') f = open('nytimes.pdf', 'wb') f.write(url.download(cached=False)) f.close()
{ "pile_set_name": "StackExchange" }
Q: When is $M \otimes_A -$ representable? Let $A$ be a commutative ring, $M$ be a $A$-module. When is $M \otimes_A - : A\text{-mod} \rightarrow A\text{-mod}$ representable? In other words, when will there exist a $A$-module $P$ s.t $M \otimes_A -=Hom(P,-)$ ? A neccessary condition is that $M$ is flat, a sufficient condition is that $M$ is free of finite rank. I wonder whether flatness or projectivity is sufficient. A: Claim: Let $M$ be a right $A$-module. The functor $M \otimes_A (-)$ from left $A$-modules to abelian groups is representable if and only if $M$ is a finitely generated projective $A$-module, in which case it can be written $\text{Hom}(M^{\ast}, -)$ where $M^{\ast} = \text{Hom}_A(M, A)$ is the dual (a left $A$-module). Proof. $\Leftarrow$: the conclusion clearly holds if $M$ is finite free. If $M$ is finitely generated projective, then writing it as a retract of a finite free module, the conclusion again holds, because retracts are absolute and commute with every functor (see this blog post, search for "the facts of life"). $\Rightarrow$: if $M \otimes_A (-) \cong \text{Hom}_A(N, -)$ then substituting $(-) = A$ gives $M \cong \text{Hom}_A(N, A)$, so $M$ is the $A$-linear dual of a module $N$ such that $\text{Hom}_A(N, -)$ commutes with colimits. This is true if and only if $N$ is finitely generated projective (see this blog post), hence a retract of a finite free module, and again using that retracts are absolute we find that $M$ is also finitely generated projective with dual $N$ (because this fact holds for finite free modules and is preserved by retracts). $\Box$ Here is some discussion of the relationship between the hypothesis that $M \otimes_A (-)$ is representable and the hypothesis that it preserves limits. Lemma: $M \otimes_A (-)$ is representable iff it preserves limits. Proof. One direction is clear. In the other direction, since $M \otimes_A (-)$ preserves colimits it is accessible, so by the presentable adjoint functor theorem, if $M \otimes_A (-)$ commutes with limits then it has a left adjoint $$L : \text{Ab} \to \text{Mod}(A).$$ This functor commutes with colimits, so by the Eilenberg-Watts theorem it must be given by $N \otimes (-)$ for some left $A$-module $N$. Taking right adjoints again, using the tensor-hom adjunction, we conclude that we have a natural isomorphism $$M \otimes_A (-) \cong \text{Hom}_A(N, -)$$ as desired. $\Box$ Next, here is a proof of $\Leftarrow$ using only the hypothesis that $M \otimes_A (-)$ commutes with limits. Claim: $M \otimes_A (-)$ commutes with limits if and only if $M$ is finitely generated projective. Proof. One direction we've already shown above. In the other direction, $M$ must in particular be flat. Assuming that $M$ is flat, $M \otimes_A (-)$ commutes with limits iff it commutes with infinite products. So consider the natural map $$M \otimes_A \prod_{i \in I} A \to \prod M \otimes_A A \cong \prod_{i \in I} M$$ for any index set $I$. Setting $I = M$, the RHS has a natural element $\prod_{m \in M} m$ which lists every element of $M$, and by hypothesis the map above is an isomorphism, so there must be an element $$\sum_{j=1}^n m_j \otimes (\prod_i a_{ij})$$ mapping to it. This element expresses every element $m \in M$ as a linear combination of a finite collection of elements $m_j$, from which it follows that $M$ is finitely generated. So far we've used the fact that this map is surjective; now let's also use the fact that it's injective. An element in its kernel is an element of the form $\sum_{j=1}^n m_j \otimes (\prod_i b_{ij})$ (the $m_j$ are the generators we just identified) such that $$\forall i \in I, \sum_{j=1}^n m_j b_{ij} = 0$$ so, in other words, it is a collection of relations the generators satisfy, and injectivity means any such element must in fact be zero in the tensor product $M \otimes_A \prod A$. Now set $I$ to index every relation that the generators satisfy, and $\sum m_j \otimes (\prod b_{ij})$ to be a list of all such relations. The condition that this element is zero in the tensor product means that it must be possible to transform it into zero using a finite sequence of applications of bilinearity, together with relations in $M$ and $\prod A$. In the process of doing this a finite number of relations in $M$ get used to transform everything to zero; these relations must then generate every relation satisfied by the generators, from which it follows that $M$ is finitely presented. Now it's enough to prove the following. Lemma: A finitely presented flat module is projective. Corollary: A module is finitely presented flat iff it's finitely generated projective. Proof. There is a proof of this in the Stacks project which I haven't looked at in detail. A more categorical proof is as follows: by Lazard's theorem, a flat module $M$ is a filtered colimit of free modules. If $M$ is finitely presented as a module then it is a compact object, meaning that $\text{Hom}(M, -)$ commutes with filtered colimits, so writing $M \cong \text{colim}_i F_i$ as a filtered colimit of free modules, we conclude that the identity $M \to M$ factors through one of the $F_i$, hence that $M$ is a retract of a free module, hence projective. $\Box$
{ "pile_set_name": "StackExchange" }
Q: Webdriver: Wait for PagetoLoad and then Scroll to Element I need to wait for a page 'popup overlay' to load before scrolling to the relevant web element. The following code below is successful when locating and scrolling to a web element but i want to avoid Thread.sleep. public void scrollToElementByLocator(WebElement element) throws InterruptedException { Thread.sleep(4000); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", element); ((JavascriptExecutor) driver).executeScript("window.scrollBy(0, -400)"); 3. Can anyone advice on another method to wait for a page to load and then scroll to the intended webelement without using thread.sleep? Many thanks for your help A: These are a pain. Ideally you would have access to the devs and they could tell you what elements appear/disappear that you can wait for. In this case, I'm assuming you don't have access to them. What I try to do is trigger the action, quickly right-click and choose Inspect element, and see what elements are popping up. If you are lucky, the dialog, etc. stays up and it's easy to find. In cases like this, they happen so briefly that it makes it really hard. What I did was to do the actions above to the point where I was triggering it on/off and watching the DOM for elements to appear/disappear. I finally got in the right place and found this using screencap and OCR <div class="modal in" id="loading-modal" data-backdrop data-keyboard="false" tabindex="-1" role= "dialog" aria-hidden="true" style="z-index: 1100; top: 475px; display: block; padding-right: 17px;" modal-dialog"> <div> id="loading-page-backdrop" class="in"></div> There are a couple of DIVs there, one of them is very likely the element you are looking for and both have IDs so they should be easy to get ahold of and wait for them to be invisible. // wait for modal to disappear new WebDriverWait(driver, 10).until(ExpectedConditions.invisibilityOfElementLocated(By.id("loading-modal"))); // do stuff Even if these aren't the elements you are looking for, you should be able to use this technique to find the ones you want. BTW, I write automation in Java and I've never needed to scroll the window... it just does it for me. Have you tried the scenario without the scroll code?
{ "pile_set_name": "StackExchange" }
Q: MvvmCross Android BackgroundColor not binding to ViewModel I'm having a tough time getting a basic MvvmCross Android example working where the BackgroundColor of the RelativeLayout is bound to the ViewModel. The app runs, some text appears, and I'm expecting my background to turn Yellow. The background color, however, remains unchanged. I have included the Hot Tuna starter pack in both my Core and Droid projects as well as the MvvmCross - Color Plugin. My Droid project was automatically given ColorPluginBootstrap.cs Layout <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:local="http://schemas.android.com/apk/res-auto" android:layout_width="fill_parent" android:layout_height="fill_parent" local:MvxBind="BackgroundColor NativeColor(BackgroundColor)"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textSize="20sp" android:gravity="center" android:text="Text to make sure the layout inflates" /> </RelativeLayout> ViewModel public class ViewModel : MvxViewModel { RGBAColorConverter _rgbaConverter; public ViewModel() { var color = "#ffedff00"; _rgbaConverter = new RGBAColorConverter(); BackgroundColor = _rgbaConverter.Convert(color); } private MvxColor _backgroundColor; public MvxColor BackgroundColor { get { return _backgroundColor; } set { _backgroundColor = value; RaisePropertyChanged(() => BackgroundColor); } } } Binding works - I've tried making other ViewModel properties that were string to do simple text binding. All of that seems just fine. I've placed debugging break points on the getter of the BackgroundColor ViewModel property and I can see the MvxColor as expected. What am I missing for my color binding scenario? I haven't done anything extra in the Setup.cs I haven't created any other wiring up classes in my Droid project I haven't created any Android-specific color converter implementations A: I've just written a test app and it seems to work for me - using 3.0.14 nuget binaries. Also, the ValueConverters test app seemed to work OK - https://github.com/MvvmCross/MvvmCross-Tutorials/tree/master/ValueConversion Looking at your sample, the only thing I can think of is that maybe you are only testing transparent colours (RGBA #ffedff00 has Alpha=0) If that isn't it, can you post more - perhaps a full sample somewhere?
{ "pile_set_name": "StackExchange" }
Q: CSS font sizing relative to parent Is there a font sizing unit in CSS that allows me to specify sizes relative to the parent element; vw and vh for example are relative to the viewport width and height respectively. I want a parent relative size for a responsive design. Say for example my parent element is 400px wide, I want my text to be half of that width, but I'm not sure if I can specify this - or even if such a feature would be widely supported. A: Just use the font-size value ising em instead of px or pt. For example, if you have a div with a width and height of 400px, use a font-size: XXem (where xx is the numeric value). Alternately, you can also include a % in your font size as well.
{ "pile_set_name": "StackExchange" }
Q: java basics static method can a static method be invoked before even a single instances of the class is constructed? A: absolutely, this is the purpose of static methods: class ClassName { public static void staticMethod() { } } In order to invoke a static method you must import the class: import ClassName; // ... ClassName.staticMethod(); or using static imports (Java 5 or above): import static ClassName.staticMethod; // ... staticMethod();
{ "pile_set_name": "StackExchange" }
Q: How do I accesses a static variable value for each instance of a class object #include <iostream> using namespace std; class Box { public: static int objectCount; // Constructor definition Box(double l = 2.0, double b = 2.0, double h = 2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; // Increase every time object is created this->objectCount++; } double Volume() { return length * breadth * height; } static int getID() { return objectCount; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Initialize static member of class Box int Box::objectCount = 0; int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 // Print total number of objects. cout << "Total objects: " << Box::objectCount << endl; cout << "Box1 ID: " << Box1.getID() << endl; cout << "Box2 ID: " << Box2.getID() << endl; return 0; } How do I access the objectCount of 'Box1' and 'Box2'. 'Box1' is supposed to have an objectCount of 1 while 'Box2' remains 2. e.g it prints: Constructor called. Constructor called. Total objects: 2 Box1 ID: 2 Box2 ID: 2 instead of: Constructor called. Constructor called. Total objects: 2 Box1 ID: 1 Box2 ID: 2 A: There is only one objectCount for the class. That's what a static class member is, by definition. What you need to do is add a non-static member to the class, and initialize it in the constructor. static int objectCount; int my_objectCount; // Constructor definition Box(double l = 2.0, double b = 2.0, double h = 2.0) : my_objectCount(++objectCount) { // ... } Then, my_objectCount will be 1 for the first instance of the class, 2 for the second one, and so on.
{ "pile_set_name": "StackExchange" }
Q: Using glib in C - correct invocation of pkg-config in a Makefile I am trying to make a web server in C. I am using the glib library which I include in my .c file with the syntax: #include <glib.h> To be able to use the library I have added the following two lines in my Makefile: CFLAGS = 'pkg-config --cflags glib-2.0' LDLIBS = 'pkg-config --libs glib-2.0' But when I compile from the Shell I get the following error messages gcc 'pkg-config --cflags glib-2.0' httpd.c 'pkg-config --libs glib-2.0' -o httpd gcc: error: pkg-config --cflags glib-2.0: No such file or directory gcc: error: pkg-config --libs glib-2.0: No such file or directory make: *** [httpd] Error 1 Is there anyone who knows a solution to this problem? A: pkg-config is a tool meant to print needed CFLAGS and LIBS to standard out, so I see kind of a "double error" here: What you probably read was giving a parameter like CFLAGS = `pkg-config --cflags glib-2.0` to make. Note the backticks here, they tell the shell to run a command and replace the whole construct with the output of that command (alternate syntax for shells is $()). Even with backticks, this wouldn't work inside a Makefile which has different syntax from sh. The corresponding construct in GNU make is $(shell ), so just write CFLAGS = $(shell pkg-config --cflags glib-2.0).
{ "pile_set_name": "StackExchange" }
Q: Refactor angular ui-router resolver to use it globally I have resolve method inside angular config. It was written to protect the view from unauthorized access. Now the problem is, if I create a different route file, I have to copy the same resolve on each file. Is there any other way so that I can write it once and use it everywhere? (function(){ 'use strict'; var app = angular.module('app'); app.config(/* @ngInject */ function($stateProvider, $urlRouterProvider) { var authenticated = ['$q', 'MeHelper', '$state', function ($q, MeHelper, $state) { var deferred = $q.defer(); MeHelper.ready() .then(function (me) { if (me.isAuthenticated()) { deferred.resolve(); } else { deferred.reject(); $state.go('login'); } }); return deferred.promise; }]; $stateProvider .state('index', { url: "", views: { "FullContentView": { templateUrl: "start.html" } } }) .state('dashboard', { url: "/dashboard", views: { "FullContentView": { templateUrl: "dashboard/dashboard.html" } }, resolve: { authenticated: authenticated } }) $urlRouterProvider.otherwise('/404'); }); })(); Edit: MeHelper is a Service. A: To refactor your code, you should register a service and take the authentication code to the service. Authenticate service: app.factory('authenticateService', ['$q', 'MeHelper', function($q,MeHelper){ var obj = {}; obj.check_authentication = function(params) { var deferred = $q.defer(); MeHelper.ready() .then(function (me) { if (me.isAuthenticated()) { deferred.resolve(); } else { deferred.reject(); $state.go('login'); } }); return deferred.promise; } return obj; } ]); Then, use this service in any route file in resolve, taking this service name in dependency injection or the function parameter, Route configuration file: (function(){ 'use strict'; var app = angular.module('app'); app.config(/* @ngInject */ function($stateProvider, $urlRouterProvider) { $stateProvider .state('index', { url: "", views: { "FullContentView": { templateUrl: "start.html" } } }) .state('dashboard', { url: "/dashboard", views: { "FullContentView": { templateUrl: "dashboard/dashboard.html" } }, resolve: { authenticated: function(authenticateService) { return authenticateService.check_authentication(); } } }) $urlRouterProvider.otherwise('/404'); }); })(); watch the below lines, this is what we changes in the route configuration to resolve. the service is injected in below lines: resolve: { authenticated: function(authenticateService) { return authenticateService.check_authentication(); } }
{ "pile_set_name": "StackExchange" }
Q: Updating only those SVG elements where the underlying bound data has been modified I have a force simulation graph using d3 v4. Each node is bound to some data, which I use for example to determine the radius of each node. The underlying bound data is updated periodically, and for some nodes it changes, and for others it stays the same. I want to be able to select just those DOM elements for which the bound data changes, so that I can highlight these elements on my graph. For example, suppose that initially my data (which is bound to the forceSimulation nodes) is: data = [{id: 1, type: 0}, {id: 2, type: 1}] and it is then updated to: data = [{id: 1, type: 1}, {id: 2, type: 1}] I'd like to be able to select just the DOM element that corresponds to id=1 so that I can for example make the colour change temporarily. The update selection contains both id=1 and id=2 - I could maintain an internal mapping of previous data values and compare, but this seems inefficient. Thanks, Adam A: If a single datum attribute can be checked to see if the bound data has changed, one method would be to track that attribute as a property using selection.property and a custom property such as type. When appending the data you could define the property fairly easily: .append("circle") .property("type",function(d) { return d.type; }); Then, when updating, you could filter based on which data are matching or not matching the property: circles.data(newdata) .filter(function(d) { return d.type != d3.select(this).property("type") }) This filter will return those elements that have changed their type. Now we can re-assign the property to reflect the new type and transition those filtered elements. The snippet below should demonstrate this, the datum is just a number one or two (represented by blue and orange), and is used to set the property type. Click on the svg to update the data, only those circles which change their datum will temporarily change their radius, while also changing their color to reflect their new datum. var svg = d3.select("body") .append("svg") .attr("width",400) .attr("height",400); var circles = svg.selectAll("circle") .data(data()) .enter("circle") .append("circle") .attr("cy",function(d,i) { return Math.floor(i/5) * 40 + 20; }) .attr("cx", function(d,i) { return i%5 * 40 + 20 }) .attr("r", 8) .attr("fill",function(d) { return (d) ? "steelblue" : "orange"}) .property("type",function(d) { return d; }); // update on click: svg.on("click", function() { circles.data(data()) .filter(function(d) { return d != d3.select(this).property("type") // filter out unchanged data }) .property("type",function(d) { return d; }) // update to reflect new data .transition() .attr("r", 20) .attr("fill","crimson") .duration(500) .transition() .attr("fill",function(d) { return (d) ? "steelblue" : "orange" }) .attr("r",8) .duration(500); }) function data() { var output = []; d3.range(20).map(function(d) { output.push(Math.round(Math.random())); }) return output; } <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
{ "pile_set_name": "StackExchange" }
Q: deviceready event not fired when app is restarted/resumed on android If I use the back button when the history is empty or home button, my app closes. If I then start/resume the app, a call to document.addEventListener('deviceready', foo); will never cause foo to run. According to the documentation, the call to addEventListener will in case of the device already being ready result in the event handler being called immediately. That however seems to not be the case. Why? According to http://docs.phonegap.com/en/1.6.0/cordova_events_events.md.html, addEventListener for deviceready should be called in the handler, but such a handler will only be called once, when the app starts the first time. Regardless if I was closing the app with the back button or the home button. A: "The Cordova deviceready event fires once Cordova has fully loaded. After the device has fired, you can safely make calls to Cordova function." I think you are searching for resume event! Otherwise you can encapsulate the eventhandler and trigger it to the resume event listener
{ "pile_set_name": "StackExchange" }
Q: cvc-elt.1: Cannot find the declaration of element 'data' These are my simple XSD and XML files, I keep getting cvc-elt.1 for the "data" node. Here is the XML <?xml version="1.0" encoding="UTF-8" ?> <data xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.w3schools.com/xml {FULL_PATH}/car_designer.xsd"> <car_designer id="1" designer_name="A C Bertelli"/> <car_designer id="2" designer_name="Adam Ty Dean Smith"/> </data> Here is the XSD <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="https://www.w3schools.com" xmlns="https://www.w3schools.com" elementFormDefault="qualified"> <xs:element name="data"> <xs:complexType> <xs:sequence> <xs:element name="car_designer" maxOccurs="unbounded"> <xs:complexType> <xs:attribute name="id" type="xs:int"></xs:attribute> <xs:attribute name="designer_name" type="xs:string"></xs:attribute> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> A: The problem is that the default namespace in the XML file is http://www.w3schools.com, but the targetNamespace in the schema is https://www.w3schools.com. Notice the difference between http and https in the uri. If you change the namespace in the XML to https (xmlns="https://www.w3schools.com"), it should work.
{ "pile_set_name": "StackExchange" }
Q: .htaccess redirect only work for some pages but not others I'm having a weird issue where my .htaccess is only redirecting some pages whilst other pages aren't being redirected. This is my current redirect condition: <Ifmodule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTP_USER_AGENT} "Firefox/[1-3]\." [NC,OR] RewriteCond %{HTTP_USER_AGENT} Opera/9\..*Version/(1[10]|[1-9])\. [NC,OR] RewriteCond %{HTTP_USER_AGENT} "Opera/[1-8]\." [NC,OR] RewriteCond %{HTTP_USER_AGENT} "MSIE [1-8]\." [NC] RewriteRule ^$ http://www.mytestingdomain.com/browser-upgrade.html [L,R=302] </Ifmodule> For example www.mytestingdomain.com/about.html will get redirected if I use IE8 but www.mytestingdomain.com/search.html won't get redirected if I use IE8. I do have one or two .htaccess files in my www folder but those are just simple .htaccess files which prevent directory listings and shouldn't affect simple HTML pages. My question is, why does my above redirect condition only work on some HTML pages and not others? Thanks A: I don't even know how any of it's redirecting because you have the pattern to only redirect root. I would change the RewriteRule so that the pattern will match any character in the URI. RewriteEngine on RewriteCond %{HTTP_USER_AGENT} "Firefox/[1-3]\." [NC,OR] RewriteCond %{HTTP_USER_AGENT} Opera/9\..*Version/(1[10]|[1-9])\. [NC,OR] RewriteCond %{HTTP_USER_AGENT} "Opera/[1-8]\." [NC,OR] RewriteCond %{HTTP_USER_AGENT} "MSIE [1-8]\." [NC] RewriteRule ^.* http://www.mytestingdomain.com/browser-upgrade.html [L,R=302]
{ "pile_set_name": "StackExchange" }
Q: Calculating the maximum basis voltage of an transistor I'm having problem with calculating this parameter, I have to calculate the maximum basis voltage of transistor for power amp with complementary transistors. So I know Uebmax(maximum emitter-basis voltage) I have this formula: Ubmax = Uebmax - Uebrest Ubmax - maximum basis voltage Uebmax - maximum emiter-basis voltage (I have this value) Uebrest - emiter-basis voltage when the transistor is in rest(there is voltage and current in the schematic but there isn't signal which to amplify). From where I can get Uebrest ? Schematic (not the best quality but it's still understandable): A: For silicon bipolar transistors you may assume that Uebrest is approximately 0.7 volts. From the facts you have presented it is not possible to calculate this. If you want to analyse your circuit by logic reasoning, assuming 0.7 volts for emitter/base is a good help. However, if your only goal is the calculation of Uebrest itself... sorry, can't help. I've got a sneaking suspicion that you are not able to express your real problem, at least it seems that you don't understand what I am trying to say. A practical approach to transistor usage is that the arrow on the symbol is the emitter, and current only flows in the direction of the arrow between collector and emitter. The current will also only flow if the emitter-base voltage is above 0.7 volts (rule of thumb), the lowest potensial being at the arrows end. Base voltage should also be less than collector voltage for PNP (arrow pointing out), or base voltage greater than Collector voltage for NPN (arrow pointing in). Generally you use collector for voltage amplification (inverted output) and emitter for current amplification. Your circuit resembles an amplifier, but the transistors are not set up correctly. It seems to me that you have put the NPN transistors in "up-side-down". That probably why you are having trouble.
{ "pile_set_name": "StackExchange" }
Q: Read encrypted text files in c# I have encypt a text file by the System.Security.Cryptography.Aes class. And I want to read it. The encrypted file is like this: 첅ꙟ䤀檐⑆놞豱놈⦜튞㌝⑾钏짼ጻ뤻諓襬ꆅ㵶�紧음즼덦힪쀗ᏢⰃ䑹ᙙ鹛賹ɗꬖ濬⇊쭩폹憺㇞䔣�❷제蠒鶰܇꼺秵Ā輱쭇뎀固쑍㘘킭мុ喀�螙돸忁葪⭻ꓻ颇弔ѯ랮 I am using this code to read this: var lines = File.ReadAllLines(encryptedtxtpath); And also with a specific encoding: var lines = File.ReadAllLines(encryptedtxtpath, System.Text.Encoding.UTF8); However the lines variable I got is totally different like this: "��_�\0I�jF$��q����)��3~$����;;�ӊl���v=]�'}LǼ�f�h����s�m�,yDY[���W�.��o�!i��ӺaT��1#E��w'����\a\a:��y\01�Gˀ��VM�6��<����U�ޙ������_j�{+��z釘_o��" How can I read the original file in my code? Any help is appreciated! A: If you want the encrypted data from the file so you can decrypt it later in code you'll want: byte[] fileBytes = File.ReadAllBytes(encryptedtxtpath); Reading the encrypted file as text will not work, because encrypted data will appear random. To decrypt fileBytes, feed it into the decryption component of the class you used to encrypt the data in the first place. You will get a byte array back. From here you can write the binary directly to disk, or, if the decrypted data is text, use: Encoding.UTF8.GetString(decrypyedbytesarray) to get a string representation of the data. Replace UTF8 with the appropriate encoding.
{ "pile_set_name": "StackExchange" }
Q: Error in SDTT for an array of hasOccupation objects using Roles: "hasOccupation is not a known valid target type for the hasOccupation property" Using JSON-LD syntax and the Schema.org vocab, per Schema.org's Occupation example 4, the following should be valid, but it is not. { "@context": "http://schema.org", "@type": "Person", "name": "Jane Smith", "sameAs": "http://en.wikipedia.org/wiki/Jane_Smith", "worksFor": { "@type": "Organization", "name": "McKinsey & Company", "url" : "http://www.mckinsey.com" }, "hasOccupation": [ { "@type": "Role", "hasOccupation": { "name": "Management Consultant" }, "startDate": "2016-04-21" }, { "@type": "Role", "hasOccupation": { "name": "Chief Strategic Officer" }, "startDate": "2013-11-14", "endDate": "2016-03-22" }, { "@type": "Role", "hasOccupation": { "name": "Vice President of Sales" }, "startDate": "2009-09-20", "endDate": "2013-10-14" } ] } Via Google's Structured Data Testing Tool: hasOccupation is not a known valid target type for the hasOccupation property. A: You are not providing the type of the hasOccupation value inside the Role. It expects an Occupation value. So this "hasOccupation": { "name": "Management Consultant" } should becomes this "hasOccupation": { "@type": "Occupation", "name": "Management Consultant" } (Same for the other occurrences.)
{ "pile_set_name": "StackExchange" }
Q: javascript formatting time from Date() object 1.) Is there a built in formatting option in javascript to display time obtained from Date() to be 12 hr format? 2.) With the script below the minutes and seconds field are displayed as 1 digit format when the values are less than 10. Is there a way force 2 digit reporting on the minutes/seconds values so that 1.. 2... 3... displays as 01... 02... 03... and so on.... function updateTime(){ var dt = new Date(); var weekday = new Array(7); weekday[0]= 'Sunday'; weekday[1] = 'Monday'; weekday[2] = 'Tuesday'; weekday[3] = 'Wednesday'; weekday[4] = 'Thursday'; weekday[5] = 'Friday'; weekday[6] = 'Saturday'; var time = weekday[dt.getDay()] + ' ' + dt.getDate() + '/' + dt.getMonth() + '/' + dt.getFullYear() + ' ' +dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds(); document.getElementById('dttime').innerHTML = time; } setInterval(updateTime, 1000); A: Make your life simple. Use Moment.js function updateTime(){ var time = moment().format('MMMM Do YYYY, h:mm:ss a'); document.getElementById('dttime').innerHTML = time; } setInterval(updateTime, 1000); JsFiddle
{ "pile_set_name": "StackExchange" }
Q: Accessing variable names of Javascript arrays Assuming I have the following javascript array: [["0", Object { name="john"}], ["1", Object { surname="white"}]]; How can i print the variable name "name" (not "john", which is its value) console.log(result[0][1] ?????); A: data[0][1] returns {name: "john"}. You can then use the Object.keys function that will return the keys of an object. It will return ['name']. Then you just have to get the first item of this array. const data = [["0", {name: "john"}], ["1", {surname: "white"}]]; console.log(Object.keys(data[0][1])[0]); console.log(Object.keys(data[1][1])[0]);
{ "pile_set_name": "StackExchange" }
Q: Is it possible to pass command-line arguments to a new isolate from spawnUri() When starting a new isolate with spawnUri(), is it possible to pass command line args into that new isolate? eg: Command line: dart.exe app.dart "Hello World" In app.dart #import("dart:isolate"); main() { var options = new Options(); print(options.arguments); // prints ["Hello World"] spawnUri("other.dart"); } In other.dart main() { var options = new Options(); print(options.arguments); // prints [] when spawned from app.dart. // Is it possible to supply // Options from another isolate? } Although I can pass data into other.dart through its SendPort, the specific use I want is to use another dart app that hasn't been created with a recievePort callback (such as pub.dart, or any other command-line app). A: As far as I can tell the answer is currently no, and it would be hard to simulate via message passing because the options would not be available in main(). I think there are two good feature requests here. One is to be able to pass options on spawn() so that a script can run the same from the root isolate or a spawned isolate. The other feature, which could be used to implement the first, is a way to pass messages that are handled by libraries before main() is invoked so that objects that main() depends on can be initialized with data from the spawning isolate.
{ "pile_set_name": "StackExchange" }
Q: how to play audio through earpiece only in windows phone 8 application I have tried with AudioRoutingManager class...but i got unauthorizedaccess exception. here is my code AudioRoutingManager audioRouting = AudioRoutingManager.GetDefault(); public AudioRoutingEndpoint ChangeAudioRoute() { var currentEndPoint= audioRouting.GetAudioEndpoint(); switch (currentEndPoint) { case AudioRoutingEndpoint.Earpiece: case AudioRoutingEndpoint.Default: return AudioRoutingEndpoint.Speakerphone; case AudioRoutingEndpoint.Speakerphone: return AudioRoutingEndpoint.Earpiece; default: throw new OperationCanceledException(); } } public void SetAudioRoute() { audioRouting.SetAudioEndpoint(this.ChangeAudioRoute()); } A: The APIs in the Windows.Phone.Media.Devices namespace require the ID_CAP_AUDIOROUTING and the ID_CAP_VOIP capability. (Add this to your manifest) Also, it's only possible to change the audio routing while in a active VOIP call. Additionally, you need to do the audio routing in your background VOIP process, and not in the foreground process.
{ "pile_set_name": "StackExchange" }
Q: MySQL UTF8 with Hibernate 3 and Spring All my tables in the schema are set to UTF-8 as the default charset, but I can't manage to get Hibernate insert correctly symbols like "é" or "ñ" (they are inserted as "é" or "ñ"). My configuration is the following: <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url" value="${db.url}"></property> <property name="username" value="${db.user}"></property> <property name="password" value="${db.password}"></property> <property name="driverClassName" value="${db.driver}"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.connection.useUnicode">true</prop> <prop key="hibernate.connection.characterEncoding">UTF-8</prop> <prop key="hibernate.connection.charSet">UTF-8</prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> I've tried adding ?useUnicode=true&characterEncoding=UTF-8 to the connection URL, but with no results... Any idea? A: Solved, it wasn't an Hibernate problem, Tomcat was not configured to encode incoming requests as UTF-8.
{ "pile_set_name": "StackExchange" }
Q: Firebug throwing excessive script errors during normal browsing I expect this might get some downvotes / closevotes but I'm going to ask anyway as I can't find an answer to this anywhere else, and I know that others who use Firebug on a daily basis must have noticed this too. When I hit many "big" sites, such as Google, Paypal, Wordpress sites (especially the admin interface after a couple of plugins are active) and others with Firebug active, it can break on atleast 2-3 errors per page request. Normally it's undefined variables or something along those lines, quite often in jQuery (although what caused that error isn't). This is very annoying >:( and much more frequent than I remember even a year ago. It happens alot on websites that you would expect to be well checked for script errors which is what I find to be the most puzzling - whenever Firebug reports an error on one of my sites, I fix it until none show up, ever. What's the difference here? What I want to know is this: has firebug's error detection gotten alot stricter recently or have the general standards of script coding gotten worse - or a mix of both? Or am I just being an idiot and have switched on super-uber-mega-strict error checking somehow? Using Firebug 1.9.1 with Firefox 11.0 on Max OSX Lion. the kind of thing I see more times a day than I should in a month: p.s error is a is null, somewhere in the jQuery source. A: You've stumbled on the fact that many big websites are badly coded.
{ "pile_set_name": "StackExchange" }
Q: UML High Level Class Diagram can somebody please explains what is a high level class diagram. As far as I know class diagram shows the association between the classes but what about high level class diagram?? A: Ok, I knew what this means, a Class Diagram contains many details. A high-level class diagram is a simple class diagram reflecting only initial domain knowledge
{ "pile_set_name": "StackExchange" }
Q: How to output the process.stderr.write to winston Using winston loggers to write contents into the files but that works only when customlogger.error is used. If the node is outputting some reference error like below ReferenceError: aksbd is not defined at /home/nigilan/Desktop/homepagelogger/app.js:53:20 at Layer.handle [as handle_request] (/home/nigilan/Desktop/homepagelogger/node_modules/express/lib/router/layer.js:95:5) at next (/home/nigilan/Desktop/homepagelogger/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/home/nigilan/Desktop/homepagelogger/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/home/nigilan/Desktop/homepagelogger/node_modules/express/lib/router/layer.js:95:5) at /home/nigilan/Desktop/homepagelogger/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/home/nigilan/Desktop/homepagelogger/node_modules/express/lib/router/index.js:335:12) at next (/home/nigilan/Desktop/homepagelogger/node_modules/express/lib/router/index.js:275:10) at /home/nigilan/Desktop/homepagelogger/app.js:38:5 at Layer.handle [as handle_request] (/home/nigilan/Desktop/homepagelogger/node_modules/express/lib/router/layer.js:95:5) How to use winston to store the errors like above ? P.S. Logging the unhandled exception is nodejs server is working fine. A: ` function formatArgs(args){ return [util.format.apply(util.format, Array.prototype.slice.call(args))]; } console.info = function(){ customlogger.info.apply(customlogger, formatArgs(arguments)); }; console.warn = function(){ customlogger.warn.apply(customlogger, formatArgs(arguments)); };` Here you can also use the default logger of winston instead of your custom logger. The gist code below has the perfect answer for this.
{ "pile_set_name": "StackExchange" }
Q: Modify live search in Alfresco Commmunity 5.0.d I am using Alfresco Community 5.0.d and trying to find the files related to live search. I would like to remove or modify the people finder in live search. Please let me know the files or way to achieve it. Share-header.get.js info is below: if (!user.isAdmin) { widgetUtils.deleteObjectFromArray(model.jsonModel, "id", "HEADER_MY_FILES"); widgetUtils.deleteObjectFromArray(model.jsonModel, "id", "HEADER_SHARED_FILES"); widgetUtils.deleteObjectFromArray(model.jsonModel, "id", "HEADER_SITES_MENU"); widgetUtils.deleteObjectFromArray(model.jsonModel, "id", "HEADER_PEOPLE"); widgetUtils.deleteObjectFromArray(model.jsonModel, "id", "HEADER_REPOSITORY"); widgetUtils.deleteObjectFromArray(model.jsonModel, "id", "HEADER_BECPG"); } //Disable people search var headerSearch = widgetUtils.findObject(model.jsonModel, "id", "HEADER_SEARCH"); if (headerSearch) { headerSearch.config.showPeopleResults = false; headerSearch.config.placeholder="Search files, sites"; } Below is extensions.xml <extension> <modules> <module> <id>Update Site Header</id> <version>1.0</version> true org.alfresco.share.header com.site-header share-header As I added below lines, now I could see that my file, shared file and other menu items being removed for user(non admin) but no changes in search box. Credit : Muralidharan <auto-deploy>true</auto-deploy> <evaluator type="default.extensibility.evaluator"/> Screenshot of html structure for search box. Below is screenshot of modules/deploy: Screenshot of debug mode : Thanks in advance A: I followed below link and it worked like a charm. https://community.alfresco.com/message/806438-re-not-able-to-disable-suggestion-in-alfresco?commentID=806438&et=watches.email.thread#comment-806438 Summary: Override the live-search-people.get.json.ftl file to produce no result for live search. Steps: Extract alfresco-remote-api-5.0.d (/Applications/alfresco-5.0.d/tomcat/webapps/alfresco/WEB-INF/lib) Goto /Applications/alfresco-5.0.d/tomcat/webapps/alfresco/WEB-INF/lib/alfresco-remote-api-5.0.d/alfresco/templates/webscripts/org/alfresco/slingshot/search and copy live-search-people.get.json.ftl Then goto Applications/alfresco-5.0.d/tomcat/shared/classes/alfresco/extension/templates/webscripts/org/alfresco/slingshot/search (create new directory if not exist) and paste the file copied earlier Open that file in editor like sublime text and replace with following code. <#import "../../repository/person/person.lib.ftl" as personLib/> <#escape x as jsonUtils.encodeJSONString(x)> { "totalRecords": 0, "startIndex": 0, "items": [ ] } Restart the tomcat and test live search. Thanks to Angel and Alex for answer followed with clarification. Interesting finding that I was using Aikau 1.0.8 Because of that the changes recommended by Muralidharan was not working (older version) so now as I move to newer version of Aikau (1.0.101) then those changes are good to go. Thank you Muralidharan! /****NOTE****/ If your using older version of Aikau (like 1.0.8) than you have to override the extension Or If your using newer version of Aikau (like 1.0.101) than you can directly make changes.
{ "pile_set_name": "StackExchange" }
Q: Expire unix or time() code after x hours I am trying to create a forgot password feature which will expire the link created after x hours. So I am storing time() data in database value when a user requests a password reset. So how can I expire it? A: three options: compare the time you saved on the db with the one you get when the user click the link Use a cron job and make it run periodically Just don't save in the db and make the link to care about everything. You could use a signature + a salt to avoid users to modify this link like: $now = time(); $sk = sh1($user_id . $now . "yoursupersalthere") $link = "http://www.example.com/forgot.php?id={$user_id}&ts={$now}&sk={$sk}" that will be the link you sent to the user. Then to make the check $ts = $_GET['ts']; $user = $_GET['id']; $sk = $_GET['sk']; if (!$sk == sh1($user_id . $now . "yoursupersalthere")) { die("bad signature"); } elseif (time() - $ts > 3600 /* or put your expiration limit */) { die('link expired'); } // do your job
{ "pile_set_name": "StackExchange" }
Q: Combine two sed commands in one line I'm looking for an in place command to change all file lines which end with :.:. From chr01 1453173 . C T 655.85 PASS . GT:AD:DP:PGT:PID 0/1:25,29:54:.:. To chr01 1453173 . C T 655.85 PASS . GT:AD:DP 0/1:25,29:54 In words, I'm basically deleting :PGT:PID and :.:. from any line ending with :.:. A: With GNU sed and Solaris sed: sed '/:\.:\.$/{s///;s/PGT:PID//;}' file If you want to edit your file with GNU sed "in place" use option -i.
{ "pile_set_name": "StackExchange" }
Q: convert List to a static string if possible I am trying to wrap my head around List<String> I have a dynamicly created array List<String> selected_tags That I would like to convert to break apart the elements and place a "%" inbetween each element so I can use the new string in a http call. Creat my new List : public List<String> selected_tags = new ArrayList<String>(); Fill my List string for (int i = 0; i < tags.length; i++) { if (selected[i] == true){ selected_tags.add(tags[i]); } } I then need to use selected_tags in my url HttpGet httpPost = new HttpGet("http://www.mywebsite.com/scripts/getData.php?tags="+ BROKEN DOWN LIST<STRING>); I would like for it to look like HttpGet httpPost = new HttpGet("http://www.mywebsite.com/scripts/getData.php?tags=tag1%tag2%tag3); A: StringBuilder s = new StringBuilder(); boolean first = true; for (String tag : selected_tags) { if (!first) s.append("%"); else first = false; s.append(tag); } String myUrlString = "tags=" + s.toString(); A: actually, you should have something like StringBuilder sb = new StringBuilder(); if(selected_tags.size() > 0) { sb.append(selected_tags.get(0); for(int i = 1 ; i < selected_tags.size(); i++) { sb.append("%"); sb.append(selected_tags.get(i)); } } return sb.toString();
{ "pile_set_name": "StackExchange" }
Q: How to convert a simple list into a data frame in python How would you go about converting a list into a python data-frame. For example: listA = [1,20,12,4] To be converted to listA 0 1 1 20 2 12 3 4 What is the simpliest way to achieve this? A: listA = [1,20,12,4] pd.DataFrame(data = listA , columns=['listA'])
{ "pile_set_name": "StackExchange" }
Q: Why do I get no line numbers from a stack trace created from Exceptions? Okay; assuming this code running in debug mode - static StackFrame GetTopFrameWithLineNumber(Exception e) { StackTrace trace = new StackTrace(e); foreach (StackFrame frame in trace.GetFrames()) { if (frame.GetFileLineNumber() != 0) { return frame; } } return null; } I'm ALWAYS returning null. Why do the stack frames have no line numbers when if I inspect the Exception.StackTrace string, it clearly does have them for any non-framework code? Is there some issue with constructing a stack trace from an exception that i'm not aware of? EDIT FOR CLARITY: In the thrown exception I can see the line numbers in the StackTrace property. I'm assuming that means I have everything else I need. A: According to the documentation on the StackTrace constructor overload that takes an exception you can't expect line numbers when creating the StackTrace that way. The StackTrace is created with the caller's current thread, and does not contain file name, line number, or column information. To get the line numbers, you need to use the overload that takes a bool as well as the exception. You also need symbol files (pdb) for line numbers. Symbol files are available for both debug and release builds.
{ "pile_set_name": "StackExchange" }
Q: Challenges about the amount and characteristics of code within an executable file loaded into memory per each process When an OS such as Windows wants to run an executable file, first it should load it into RAM. Due to prevent wasting the memory, loading it partly into the memory seems more intellectual than to load it entirely. So under the condition like that, my questions are: What happens exactly when the controls arrives to an instruction like JMP containing an address out of range the loaded code? In other words how does the OS recognize that it must stop executing the instruction to avoid jumping to a irrelevant address and how does it calculate which page the related address situated in? How many pages of code does the OS copy into RAM before jumping to the entry point of a program? I mean whether the OS always copies the fixed amount of code or fixed number of pages into RAM necessarily or it could be uncertain? If the OS makes a decision that how much code or how many pages should be loaded into memory so what conditions are considered till the decision like that is made? Thanks to all. A: A modern OS's program loader basically uses mmap, not read. https://en.wikipedia.org/wiki/Memory-mapped_file#Common_uses says: Perhaps the most common use for a memory-mapped file is the process loader in most modern operating systems (including Microsoft Windows and Unix-like systems.) This creates a file-backed private mapping. (https://en.wikipedia.org/wiki/Virtual_memory). ... In other words how does the OS recognize that it must stop executing the instruction to avoid jumping to a irrelevant address and how does it calculate which page the related address situated in? In that case code-fetch causes a page fault, just like if your code loaded from part of a big static array that wasn't loaded from disk yet. After possible loading the page from disk (if it wasn't already present in the page cache) and updating the page tables, execution resumes at the address that faulted, to retry the instruction. The CPUs virtual memory hardware ("MMU", although that's not actually a separate thing in a modern CPU) handles detection of loads/stores/code-fetch from unmapped addresses. (Unmapped according to the actual page tables the HW can see. When a process "logically" has some memory mapped, but the OS is being lazy about it, we say the memory isn't "wired" into the page tables, so a page fault will bring it into memory if it's not already, and will wire it up in the page tables so the HW can access it (after a TLB miss to trigger a hardware page-walk.) If there are any runtime symbol relocations, aka fixups, to account for the program being loaded at a base address other than the one it was linked for if it needs any absolute addresses in memory, they may require writing pages of code or otherwise-read-only data, dirtying the virtual memory page so it's backed by the pagefile instead of the executable on disk. e.g. if your C source includes int *foo = &bar; at global scope, or int &foo = bar; How many pages of code does the OS copy into RAM before jumping to the entry point of the program? The program loader probably has some heuristics to make sure the entry point and maybe some other pages are mapped before trying the first time. Other than that IDK if there are any special heuristics in the virtual-memory code for executables / libraries vs. non-executable mappings. A: The processor divides the address space into sets of addresses called pages. On x86 a typical page is of size 4KiB but other sizes are possible (e.g. 1GiB, 2 MiB). Pages are continuous, so the first page is from address 0x00000000 to address 0x00000fff, for each address there is a unique page associated with it. A page has a set of attributes, the whole point of paging is to associate a set of attributes to each address. Since doing it for every single address would be too prohibitive, pages are used instead. All the addresses in a page share the same attribute. I somewhat simplified the story by not differentiating between virtual addresses (the ones that actually are paginated, i.e. they can have attributes) and physical addresses (the real addresses to use, a virtual address can be mapped to a different physical address). Among the various attributes there are: One that tells the CPU if the page is to be considered not loaded. Basically, this makes the CPU generate an exception when an instruction tries to access the page (e.g. read from it, including execution, or writing to it). Permissions Like read-only, non-executable, supervisor, etc. The physical address The main use of paging is isolation, it can be accomplished by letting the same virtual address X be mapped into different physical addresses Y1 and Y1 for the process P1 and P2 respectively. Remember that these attributes are per-page, they apply to the whole range of addresses in a page (e.g. they affects 4 KiB addresses for a 4 KiB page). With this in mind: When a process is created all its pages are marked as non-present. Accessing them would make the CPU fault. When the OS loads the program, a minimal set of pages are loaded (e.g. the kernel, part of it, the common libs, part of the program code and data) and marked present. When the program accesses a page not loaded the OS checks if the address was allocated by the program, if so (this is a valid page fault) it loads the page and resumes execution. If the address was not allocated, an invalid page fault occurs and the exception reported to the program itself. I don't know the exact number of pages loaded, one could verify it in different ways, including taking a look at the Linux kernel (for the Linux case). I'm not doing it because the actual strategy used may be complex and I don't find it particularly relevant: the OS could load the whole program if it is small enough and the stress on the memory is low. There could be settings to tweak to chose one or another strategy. In general, it is reasonable to assume that only a fixed number of pages is loaded optimistically. Factors that influence the decision could be: the amount of memory available, the priority of the process loaded, policy on the system made by the sysadmin (to prevent bloating it), type of the process (a service like a DBMS could be marked as memory intensive), restriction of the program (e.g. in a NUMA machine a process may be marked to use, prevalently, local memory, thereby having access to less memory than the total available), euristics implemented by the OS (e.g. it know that the last execution required K pages of code/data within M milliseconds from the start). To put it simply, and short, the algorithm used to load the optimal number of pages has to predict the future a bit, so the usual considerations of the case are made (i.e. assumptions, simplifications, data collection and similar).
{ "pile_set_name": "StackExchange" }
Q: How should I scaffold this express & backbone application? I never found an answer that really hit me so I'm just thought I'd put out this question and see what people thought. Here are the details of my app so far: Backend: Php Api serving up JSON Frontend: Express to serve up login / sales / signup / app pages Backbone / AMD to serve up the single page application Questions: How should I scaffold this application? I will have backbone views for the signup and login page that work through express to connect to the API...where should these be and/or is this overkill? All authentication happens through the api which passes back a session token. A: Here is what I ended up doing: client / widgets / views / models / collections / login.coffee main.coffee client-dist / server / views / app.coffee config.coffee server-dist / Details: Dist Directories: Build directories with compiled .coffee and .less files Build Tool: Grunt.js --> see this issue for details on build config Require Multi-Page Shim: I want to serve up multiple pages with AMD and followed the multi-page shim example provided by jrburke Application Management: I used Addy Osmani's Aura framework that was modified to manage application pages and widgets The node express application is served up at server-dist/app.js and loads the proper .js file from the client-dist with requirejs.
{ "pile_set_name": "StackExchange" }
Q: How to modify React component to use hooks? Below is a login component without hooks. This component has two input fields and a submit button. How can we modify this component to use hooks and convert this component into a functional component that can use states? import React from 'react'; import { userService } from '../services/user.services'; class Login extends React.Component { constructor(props) { super(props); this.state = { username: '', password: '', submitted: false, loading: false, error: '' } this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(e) { e.preventDefault(); this.setState({ submitted: true }); const data = this.state; userService.login(data.username, data.password) .then( user => { const { from } = this.props.location.state || { from: { pathname: "/" } }; this.props.history.push(from); } ); } handleChange(e) { const { name, value } = e.target; this.setState({ [name]: value }); } render() { const { ...data } = this.state; return ( <div className="login-box"> <h1>Travel With Us</h1> <form onSubmit={this.handleSubmit}> <div className="text-box"> <i className="fa fa-user"></i> <input type="text" name="username" defaultValue={data.username} onChange={this.handleChange} placeholder="Username" /> </div> <div className="text-box"> <i className="fa fa-lock" /> <input type="password" name="password" defaultValue={data.password} onChange={this.handleChange} placeholder="Passward" /> </div> <button className="btn" value="login">Sign in</button> </form> </div> ); } } export default Login; A: Below is the sample code which I have converted to use hooks. import React, { useState } from 'react'; import { userService } from '../services/user.services'; const LoginHooks = (props) => { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [submitted, setSubmit] = useState(false); let handleSubmit = function (e) { e.preventDefault(); console.log(submitted); setSubmit(true); userService.login(username, password) .then( user => console.log(user) ); }; return ( <div className="login-box"> <h1>Login</h1> <form onSubmit={handleSubmit}> <div className="text-box"> <i className="fa fa-user"></i> <input type="text" name="username" defaultValue={username} onChange={({target}) => setUsername(target.value)} placeholder="Username" /> </div> <div className="text-box"> <i className="fa fa-lock" /> <input type="password" name="password" defaultValue={password} onChange={({target}) => setPassword(target.value)} placeholder="Passward" /> </div> <button className="btn" value="login">Sign in</button> </form> </div> ); } export default LoginHooks;
{ "pile_set_name": "StackExchange" }
Q: How do you usually return an instance of a user-defined type allocated on the local stack I am curious about prevalent methodologies. I found myself doing both of these things interchangeably: Note in all cases the object is allocated locally. std::string GetDescription () { std::string desc; /* Create a description */ return desc; } void GetResult (map<int, double> & resultMap) { /*Fill map result map with values*/ } map<int, double> GetResult2(map<int, double> & resultMap) { map<int, double> & resultMap /* Fill map result map with values */ return resultMap; } What is the preferred way to do this? A: It greatly depends on the task at hand. I would go for the first approach for functions that create new values while using the second approach for functions that change the parameters. As mentioned by others, in some cases other restrictions (cost of creation / assignment) can affect the decision. The first definition is clearly stating that it will create a new object out of nothing and will return it. That is, the same definition is stating the semantics of the call. The second and third definitions require the caller to create an object before calling the function. This can be a hassle to the user as she cannot just ignore the return value (or use it as an unnamed temporal to feed another function, see snippet 1), and can be limited in cases (i.e. cannot reassign a reference from an already created object, see snippet 2). It is not clear from the function definition what is the use of the parameter inside the function. Will the behavior of the function differ depending on the passed object? It is not clear from the function definition. The third type is, I believe, the worst option. Not only it forces the caller to create a named variable to pass to the function but also makes a copy to return (unless it was a typo and you are returning a [possibly const] reference) At any rate, other considerations can unbalance the advantage of clear semantics that the first approach provides. In some cases performance, or other limitations like objects that cannot be copied (see snippet 3) // snippet 1 // user code to the different approaches class X {}; X f1(); void f2( X& ); X f3( X& ); void g( X const & ); void test1() { g( f1() ); // valid code } void test2() { X x; // must create instance before f2( x ); // then call the function g( x ); } void test3() { X x; // must create instance before g( f3( x ) ); } // snippet 2 class Y {}; class X { public: X( Y & y ) : y_( y ) {} private: Y & y_; }; X f1(); void f2( X & ); X f3( X & ); void test1() { X x = f1(); } void test2or3() { Y y; X x( y ); // user must create with a reference f2( x ); // f2 cannot change the reference inside x to another instance } // snippet 3 class X { private: X( X const & ); X& operator= ( X const & ); }; X f1(); // Returned object cannot be used void f2( X & ); X f3( X & ); void test1() { X x = f1(); // compilation error } void test2() { X x; f2( x ); } void test3() { X x; X y = f3( x ); // compilation error }
{ "pile_set_name": "StackExchange" }
Q: PHP Regular Expression select between characters or to end of string I have been working on this problem for several days and it's starting to drive me crazy. I'm comfortable using regular expressions but this one thing seems to be escaping me. I need to match a string between a set of characters if they exist otherwise it should match to the end of the line. For example: I'm just trying to get "content" out of the following example: $str1="title:content @description" $str2="title:content" preg_match("/:(.*?)[(@)|(:)|(\*)]?$/",$str1,$content); preg_match("/:(.*?)[(@)|(:)|(\*)]?$/",$str2,$content); $str1 outputs:"content @description" $str2 outputs:"content" note: the strings may be in a different order or may not have a special character (@,:,or *) in it or they might have one so there's no "end of string" character that will be common besides "end of line". I've tried every combination i can think of to make the entire "or" statement conditional and read a ton of posts with similar but not quite the same question. A: You can write: preg_match("/:(.*?)(?:[@:*]|$)/", $str1, $content); (note that the match ends at one of @:* or end-of-string, using |; your version has the [@:*] optional, but makes the end-of-string mandatory.) or simply: preg_match("/:([^@:*]*)/", $str1, $content); (meaning "a colon, followed by zero or more characters that aren't in @:*").
{ "pile_set_name": "StackExchange" }
Q: mongodb query child collection count in aggregate group I have a mongo newbie question I have a cars collection, that has a features array I'm trying to group cars by make - and sum all features for that make this is an analogy, as what I'm working on is a financial application with a similar problem, so Having the following documents in a collection: /* 1 */ { "_id" : ObjectId("5ad870ed22b6ac63f3b66359"), "make" : "toyota", "model" : "corolla", "year" : 1992, "type" : "sedan", "features" : [] } /* 2 */ { "_id" : ObjectId("5ad8712222b6ac63f3b66367"), "make" : "toyota", "model" : "camry", "year" : 2014, "type" : "sedan", "features" : [ "cruise control", "air conditioning", "auto headlights" ] } /* 3 */ { "_id" : ObjectId("5ad8714122b6ac63f3b6636c"), "make" : "toyota", "model" : "celica", "year" : 2003, "type" : "sports hatch", "features" : [ "cruise control", "air conditioning", "turbo" ] } /* 4 */ { "_id" : ObjectId("5ad8733722b6ac63f3b663a9"), "make" : "mazda", "model" : "323", "year" : 1998, "type" : "sports hatch", "features" : [ "powered windows", "air conditioning" ] } /* 5 */ { "_id" : ObjectId("5ad8738022b6ac63f3b663af"), "make" : "mazda", "model" : "3", "year" : 2014, "type" : "sports hatch", "features" : [ "powered windows", "air conditioning", "cruise control", "navigation" ] } /* 6 */ { "_id" : ObjectId("5ad873b322b6ac63f3b663b6"), "make" : "mazda", "model" : "cx9", "year" : 2012, "type" : "sports utility vehicle", "features" : [ "powered windows", "air conditioning", "cruise control", "navigation", "4 wheel drive", "traction control" ] } I want to group the cars by make , and count all the parts db.getCollection('cars').aggregate([ { $match : { $or : [{ make : "toyota"}, { make : "mazda"}] } }, { $group: { _id: '$make', count: { $sum: { $count : "$features" } } }, } ]) I can't get the $count to work that way, to just count the features for each item grouped suggestions ? A: I think you can first group by make, sum the length of features, something like this: db.getCollection('myCollection').aggregate([ { "$group": { "_id": "$make", "count": { "$sum": { "$size": "$features" } } } } ])
{ "pile_set_name": "StackExchange" }
Q: Delete number even numbers from numpy array I'm working using python 3.x on Windows 10. I have a numpy array of size 1848. I need to delete even numbers from this array. I tried following thing len=arr.size for i in range(1,len-1): if (arr[i]%2==0): result=np.where(arr==arr[i]) result=int(result[0]) np.delete(arr,result,axis=0) len=len-1 But it's not working. Can you suggest me how to do this? A: import numpy as np a = np.random.randint(10, size=10) [4 3 9 9 9 4 3 4 3 2] a[a%2!=0] [3, 9, 9, 9, 3, 3]
{ "pile_set_name": "StackExchange" }
Q: How to achieve this sprite/mesh tile splitting like in Peggle? Everyone knows Peggle. Here's a simple screenshot from one of their 'shapes': On the first look, it looks so simple. It's a circle made of identical tiles: It's easy to make a circle like this, even programatically. But then I realised that I can't make bigger/smaller circles with this single tile. For instance, the shape above has 17 tiles. If I want to make a circle with 9 tiles, I need to make a tile more curved, so it can close the entire shape with 9 elements. Here's a sample of a shape which cannot be constructed using the above tile: As you can see, it's probably made dynamically. Each tile has different size and it's warped differently and I don't think so that they've used 30000 types of tiles with multiple angles. They did actually, in the first version of the game coded in Lua, but there were 3-5 types of tiles. In their latest game, they've created more exotic shapes, and that would be so inefficient, especially for mobiles. Are there any algorithms for filling an oval or circle with irregular tiles like this? I assume I'd need to split some meshes dynamically for that, or at least sprites. I'll be thankful for pointing me a right direction! A: This can be done in general using a shape where you can get the normals at any point. It's particularly easy if the shape is a circle or an ellipse, because we can just use the parametric equation for the ellipse to give the position and normal. One of the problems now is that to cut up the curve into segments, you should know the arc-length of each segment. This can be a bit tricky when you are dividing the curve up in "parameter space" instead of "real space" you can see it in the picture in the question, where they are squished around where the curvature is higher. This will happen when you divide up into equal angle segments and you might need to adjust for that. So let's say we have divided our curve into segments, equal or otherwise, then we can create custom geometry from the position and normal. Choose point a to be one point and b is the next point. We build a custom geometry as a quad using the four points a + a_normal a - a_normal b - b_normal b + b_normal This image is showing two adjacent points on the curve and their normals. Four more points are generated from them. Interactive example. This was made in javascript but should translate into Unity.
{ "pile_set_name": "StackExchange" }
Q: Improving the footnote on my table I would like to use the following code to make a nice table, but I'm irritated by the inability to make the footnote of the table look nicer. FYI, I have printed this code directly from Stata using esttab, just the way I like it, so I'm not concerned about the table per se, rather only with the footnote. Any thoughts? Thanks! The issue is that my fourth column shifts too far to the right. If I make many rows in the footer of the table, I can solve this problem, but then it looks ridiculously long. I would like to try to space out these four columns more evenly, so that I can reduce the height of the footnote. \begin{table}[htbp]\centering \footnotesize \def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} \caption{Rural Determinants of Gold Expenditure Incidence: comparing Pooled OLS with FE and RE models} \begin{tabular}{l*{3}{c}} \hline\hline &\multicolumn{1}{c}{Pooled OLS}&\multicolumn{1}{c}{FE Model}&\multicolumn{1}{c}{RE Model}\\ \hline $MPCE_{nt}$ & 0.931\sym{**} & 0.883\sym{***}& 0.983\sym{***}\\ & (0.356) & (0.319) & (0.325) \\ [1em] $MPCE^{2}_{nt}$ & -0.017\sym{**} & -0.018\sym{**} & -0.017\sym{*} \\ & (0.007) & (0.007) & (0.010) \\ [1em] $MaleWage_{nt}$ & 0.520 & 0.479 & 0.670\sym{***}\\ & (0.450) & (0.332) & (0.233) \\ [1em] $MaleWage^{2}_{nt}$ & -0.008 & -0.008 & -0.010\sym{***}\\ & (0.006) & (0.005) & (0.004) \\ [1em] $FemaleWage_{nt}$ & -1.794\sym{***}& -1.418\sym{***}& -1.513\sym{***}\\ & (0.465) & (0.424) & (0.397) \\ [1em] $FemaleWage^{2}_{nt}$ & 0.061\sym{***}& 0.051\sym{***}& 0.060\sym{***}\\ & (0.014) & (0.014) & (0.016) \\ \hline Observations & 264 & 264 & 264 \\ $R^2$ & 0.768 & 0.113 & \\ \hline\hline \multicolumn{4}{l}{Note: Dependent variable is $IncidenceGold_{nt}$ in every} \\ \multicolumn{4}{l}{estimation. The agricultural controls which have been used thus far,} \\ \multicolumn{4}{l}{i.e., $Output_{nt}$, $Foodprice_{nt}$, $Rainfall_{nt}$, and} \\ \multicolumn{4}{l}{$Rainfall_{nt-1}$, have been included, but are not reported.} \\ \multicolumn{4}{l}{Heteroskedastic and Autocorrelation Consistent (HAC) robust standard} \\ \multicolumn{4}{l}{errors are clustered at the district level and reported in the} \\ \multicolumn{4}{l}{parentheses. * p<0.10, ** p<0.05, and *** p<0.01}\\ \end{tabular} \end{table} A: like this? with use of packages booktabs (for rules in table), threeparttable (for tnote and note below table), siunitx (for numbers align at decimal points) and caption (for beter caption formatting): \documentclass{article} \usepackage{siunitx} % <-- package used in table \usepackage{booktabs, threeparttable} % <-- packages used in table \renewcommand{\tnote}[1]{\textsuperscript{#1}} \usepackage[skip=1ex]{caption} \begin{document} \begin{table}[htbp] \centering \caption{Rural Determinants of Gold Expenditure Incidence: comparing Pooled OLS with FE and RE models} \begin{threeparttable} \begin{tabular}{ l *{3}{S[table-format=-1.3, table-space-text-post={***}, input-symbols = {(- )}]} } \toprule%\hline\hline & {Pooled OLS} & {FE Model} & {RE Model} \\ \midrule%\hline $MPCE_{nt}$ & 0.931\tnote{**} & 0.883\tnote{***}& 0.983\tnote{***} \\ & (0.356) & (0.319) & (0.325) \\ \addlinespace $MPCE^{2}_{nt}$ & -0.017\tnote{**} & -0.018\tnote{**} & -0.017\tnote{*} \\ & (0.007) & (0.007) & (0.010) \\ \addlinespace $MaleWage_{nt}$ & 0.520 & 0.479 & 0.670\tnote{***} \\ & (0.450) & (0.332) & (0.233) \\ \addlinespace $MaleWage^{2}_{nt}$ & -0.008 & -0.008 & -0.010\tnote{***} \\ & (0.006) & (0.005) & (0.004) \\ \addlinespace $FemaleWage_{nt}$ & -1.794\tnote{***}& -1.418\tnote{***}& -1.513\tnote{***} \\ & (0.465) & (0.424) & (0.397) \\ \addlinespace $FemaleWage^{2}_{nt}$ & 0.061\tnote{***}& 0.051\tnote{***}& 0.060\tnote{***} \\ & (0.014) & (0.014) & (0.016) \\ \midrule%\hline Observations & {264} & 264 & 264 \\ $R^2$ & 0.768 & 0.113 & \\ \bottomrule%\hline\hline \end{tabular} \begin{tablenotes}[flushleft]\footnotesize \item[] Note: Dependent variable is $IncidenceGold_{nt}$ in every estimation. The agricultural controls which have been used thus far, i.e., $Output_{nt}$, $Foodprice_{nt}$, $Rainfall_{nt}$, and $Rainfall_{nt-1}$, have been included, but are not reported. \item[] Heteroskedastic and Autocorrelation Consistent (HAC) robust standard errors are clustered at the district level and reported in the parentheses. \item[] * $p<0.10$, ** $p<0.05$, and *** $p<0.01$ \end{tablenotes} \end{threeparttable} \end{table} \end{document} addendum: with use of threepartablex package with option referable for the note below of the table you can use command \note. also with defining a little bit wide S columns and use more correct syntax for variables named by words, the table become: modified mwe is: \documentclass{article} \usepackage{amsmath} % <-- package used in table \usepackage{siunitx} % <-- package used in table \usepackage{booktabs} % <-- packages used in table \usepackage[referable]{threeparttablex} % <-- packages used in table \renewcommand{\tnote}[1]{\textsuperscript{#1}} \usepackage[skip=1ex]{caption} \begin{document} \begin{table}[htbp] \centering \caption{Rural Determinants of Gold Expenditure Incidence: comparing Pooled OLS with FE and RE models} \label{tab:my table} \begin{threeparttable} \begin{tabular}{>{$}l<{$} % <--- changed *{3}{S[table-format=-1.3, table-space-text-post={***}, input-symbols = {(- )}, table-column-width=6em]} % <--- added } \toprule & {\text{Pooled OLS}} & {FE Model} & {RE Model} \\ \midrule \mathit{MPCE}_{nt} & 0.931\tnote{**} & 0.883\tnote{***}& 0.983\tnote{***} \\ & (0.356) & (0.319) & (0.325) \\ \addlinespace \mathit{MPCE}^{2}_{nt} & -0.017\tnote{**} & -0.018\tnote{**} & -0.017\tnote{*} \\ & (0.007) & (0.007) & (0.010) \\ \addlinespace \mathit{MaleWage}_{nt} & 0.520 & 0.479 & 0.670\tnote{***} \\ & (0.450) & (0.332) & (0.233) \\ \addlinespace \mathit{MaleWage}^{2}_{nt} & -0.008 & -0.008 & -0.010\tnote{***} \\ & (0.006) & (0.005) & (0.004) \\ \addlinespace \mathit{FemaleWage}_{nt} & -1.794\tnote{***} & -1.418\tnote{***}& -1.513\tnote{***} \\ & (0.465) & (0.424) & (0.397) \\ \addlinespace \mathit{FemaleWage}^{2}_{nt} & 0.061\tnote{***} & 0.051\tnote{***}& 0.060\tnote{***} \\ & (0.014) & (0.014) & (0.016) \\ \midrule \text{Observations} & {264} & 264 & 264 \\ R^2 & 0.768 & 0.113 & \\ \bottomrule \end{tabular} \begin{tablenotes}[flushleft]\footnotesize\parindent=1em \note Dependent variable is $\mathit{IncidenceGold}_{nt}$ in every estimation. The agricultural controls which have been used thus far, i.e., $\mathit{Output}_{nt}$, $\mathit{Foodprice}_{nt}$, $\mathit{Rainfall}_{nt}$, and $\mathit{Rainfall}_{nt-1}$, have been included, but are not reported. Heteroskedastic and Autocorrelation Consistent (HAC) robust standard errors are clustered at the district level and reported in the parentheses. \item[] * $p<0.10$, ** $p<0.05$, and *** $p<0.01$ \end{tablenotes} \end{threeparttable} \end{table} \end{document} A: Here is a solution based on threepartable and siunitx. I've added some colour: \documentclass[review,authoryear,11pt]{elsarticle} \usepackage{mathtools} \usepackage{setspace} \usepackage{threeparttable, booktabs, makecell, caption} \usepackage{siunitx} \usepackage[svgnames, table]{xcolor} \renewcommand\theadfont{\normalsize\bfseries} \newcommand{\MPCE}{\mathit{MPCE}} \newcommand{\MW}{\mathit{MaleWage}} \newcommand{\mW}{\textit{MaleWage}} \newcommand{\FW}{\textit{FemaleWage}} \begin{document} \begin{table}[htbp]\centering \footnotesize \def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} \arrayrulecolor{LightSlateGray} \begin{threeparttable} \caption{Rural Determinants of Gold Expenditure Incidence: comparing Pooled OLS with FE and RE models} \sisetup{table-format = -1.3, table-space-text-post = ***, table-align-text-post = false, table-space-text-pre = (, table-align-text-pre = false} \begin{tabular}{l*{3}{S}} \toprule \specialrule{0.4pt}{1.2pt}{\belowrulesep} & {Pooled OLS} & {FE Model} & {RE Model}\\ \midrule $\MPCE_{nt}$ & 0.931\sym{**} & 0.883\sym{***}& 0.983\sym{***}\\ & {(}0.356{)} & {(}0.319{)} & {(}0.325{)} \\ [1em] $\MPCE^{2}_{nt}$ & -0.017\sym{**} & -0.018\sym{**} & -0.017\sym{*} \\ & {(}0.007{)} & {(}0.007{)} & {(}0.010{)} \\ [1em] $\MW_{nt}$ & 0.520 & 0.479 & 0.670\sym{***}\\ & {(}0.450{)} & {(}0.332{)} & {(}0.233{)} \\ [1em] $\MW^{2}_{nt}$ & -0.008 & -0.008 & -0.010\sym{***}\\ & {(}0.006{)} & {(}0.005{)} & {(}0.004{)} \\ [1em] $\FW_{nt}$ & -1.794\sym{***}& -1.418\sym{***}& -1.513\sym{***}\\ & {(}0.465{)} & {(}0.424{)} & {(}0.397{)} \\ [1em] $FW^{2}_{nt}$ & 0.061\sym{***}& 0.051\sym{***}& 0.060\sym{***}\\ & {(}0.014{)} & {(}0.014{)} & {(}0.016{)} \\ \midrule Observations & {264} & {264} & {264} \\ $R^2$ & 0.768 & 0.113 & \\ \specialrule{0.4pt}{\aboverulesep}{1.2pt}\bottomrule \end{tabular}% \smallskip\scriptsize \begin{tablenotes}[flushleft] \item[]\textit{Note}: Dependent variable is $\mathit{IncidenceGold}_{nt}$ in every estimation. The agricultural controls which have been used thus far, i.e. $\mathit{Output}_{nt}$, $\mathit{Foodprice}_{nt}$, $\mathit{Rainfall}_{nt}$, and $\mathit{Rainfall}_{nt-1}$, have been included, but are not reported. \smallskip \item[] Heteroskedastic and Autocorrelation Consistent (HAC) robust standard errors are clustered at the district level and reported in the parentheses. \smallskip \item[]* $ p<0.10 $, \enspace ** $ p<0.05 $, and\enspace *** $ p<0.01 $. \end{tablenotes} \end{threeparttable} \end{table} \end{document} A: For these types of situations I try to use either tabu or longtabu, these provide a lot more features, such as automatic newline when needed, longtabu can be used if the table is too long for the page to make it go over the page, making sure the correct lable and everything is assigned. Not completely your code, but this is how I would solve your problem: \documentclass[a4paper]{article} \usepackage{tabu} \usepackage{longtable} \usepackage{booktabs} \usepackage[singlelinecheck=false]{caption} %Use this to set the align to left \begin{document} \centering \footnotesize \begin{longtabu} spread \textwidth{l X[c] X[c] X[c]} \caption{Rural Determinants of Gold Expenditure Incidence: comparing Pooled OLS with FE and RE models} \\ \toprule \rowfont[c]{\bfseries} & Pooled OLS & FE Model & RE Model\\ \midrule $MPCE_{nt}$ & 0.931** & 0.883*** & 0.983***\\ & (0.356) & (0.319) & (0.325) \\ &&&\\ $MPCE^{2}_{nt}$ & -0.017** & -0.018** & -0.017* \\ & (0.007) & (0.007) & (0.010) \\ &&&\\ $MaleWage_{nt}$ & 0.520 & 0.479 & 0.670***\\ & (0.450) & (0.332) & (0.233) \\ &&&\\ $MaleWage^{2}_{nt}$ & -0.008 & -0.008 & -0.010***\\ & (0.006) & (0.005) & (0.004) \\ &&&\\ $FemaleWage_{nt}$ & -1.794*** & -1.418*** & -1.513***\\ & (0.465) & (0.424) & (0.397) \\ &&&\\ $FemaleWage^{2}_{nt}$ & 0.061*** & 0.051*** & 0.060***\\ & (0.014) & (0.014) & (0.016) \\ \midrule Observations & 264 & 264 & 264 \\ $R^2$ & 0.768 & 0.113 & \\ \bottomrule \multicolumn{4}{l}{Note: Dependent variable is $IncidenceGold_{nt}$ in every} \\ \multicolumn{4}{l}{estimation. The agricultural controls which have been used thus far,} \\ \multicolumn{4}{l}{i.e., $Output_{nt}$, $Foodprice_{nt}$, $Rainfall_{nt}$, and} \\ \multicolumn{4}{l}{$Rainfall_{nt-1}$, have been included, but are not reported.} \\ \multicolumn{4}{l}{Heteroskedastic and Autocorrelation Consistent (HAC) robust standard} \\ \multicolumn{4}{l}{errors are clustered at the district level and reported in the} \\ \multicolumn{4}{l}{parentheses. * p<0.10, ** p<0.05, and *** p<0.01}\\ \end{longtabu} \end{document} It produces this table: I hope this is what you were looking for EDIT: Added the left align for the table caption, preview:
{ "pile_set_name": "StackExchange" }
Q: removing NT AUTHORITY\authenticated users vs all authenticated users and adding domain group instead I have a root site collection and under the "Style Resources Readers group" i have the NT AUTHORITY\authenticated and the all authenticated users . Are these the same groups but with different names? I know the is everyone that can logon o your network. But i would like to use a domain group instead of the NT AUTHORITY\authenticated? How can i achieve this? If i remove the group "NT AUTHORITY\authenticated" how can i add it back? When i tried to add another one i couldn't find it :( Anyway the mean question ican't find anywhere is how can i restrict some users on the site collection if i don't want everyone to have access? Thanks in advance A: I would advice not to mess up with these settings. The master page library, as well as the style library (and a few other libraries) requires specific permissions to ensure that everyone (even the one with limited access) can still access to the branding / layout ressources. Since it's somehow mandatory to allow anyone to consume these resources (and will not bring a security breach) I would simply not change it. You might bring additional issue that will be very hard to identify / fix if not documented properly (eg: your AD group users are slightly changed, etc.) A: All Authenticated covers all security types where NT AUTHORITY are only the local domain users, so if you are only using local domains they are the same. The best way of achieving what you want is with active directory, this will allow you to make custom groups for all the users properly, and to make your own blanket permissions.
{ "pile_set_name": "StackExchange" }
Q: javascript,searching my name I am making a program in javascript which searches my name in a text and logs the frequency of the same in the console. I am first checking each letter of the text and when it matches with my name's first letter, I use another for loop which pushes letters into an array named hits.The letters from string "text" are pushed upto the length of my name using push(). After this I check whether the array "hits" and string "myName" are equal,and if they are equal I increase the count by one. But my code is not working and I don't know why,I have thought on it very much but all went in vain. Please help. var text="abhishek apolo bpple abhishek",myName="abhishek",hits=[]; var count=0; for(i=0;i<text.length;i++) { if(text[i]===myName[0]) { for(j=i;j<(i+myName.length);j++) { hits.push(text[j]); } } if(myName==hits) { hits=[]; count=count+1; } hits=[]; } if(count===0) console.log("Name not found!"); else console.log(count); A: your code is failing because you are comparing array to string, which would give you false, you can get string from array string using join(), or a better method would be to use regular expression, like this: var text="abhishek apolo bpple abhishek",myName="abhishek",hits=[]; var count=0; console.log((text.match(new RegExp(myName, 'g'))).length);
{ "pile_set_name": "StackExchange" }
Q: Show "show more" button and hide second line I'm totally lost here. I'm trying to display information on my website on only using one line of text. If more info need to be shown, the extra info will be shown on second line. But how can I hide the second line and show a button "show more" instead? Once the user clicks on the show more button, the extra info/texts on second line will only be shown. Thanks... Below is my javascript for the button, I have no idea how to code the html part where the second line will be hidden automatically and display the "show more" button. var hide2 = 1; $('#showmorerates').click(function(){ if(hide2 == 1){ $('.morerates').toggle(300); document.getElementById("showmorerates").innerHTML = '<a>Show Less</a>'; hide2 = 0; } else { $('.morerates').toggle(300); document.getElementById("showmorerates").innerHTML = '<a>Show More</a>'; hide2 = 1; } }); A: Just use a css class to set height of the div and overflow to hidden. Whenever show more button is clicked, remove this class from the text container. .less { overflow: hidden; height: 1em; } Here is the working fiddle: http://jsfiddle.net/2tg7v/
{ "pile_set_name": "StackExchange" }
Q: Why didn't Kreacher disapparate with Regulus from the cave? When Kreacher tells his story in the Deathly Hallows he says Regulus ordered him to leave him behind and disapparate himself. But why wouldn't Regulus save himself? We know that house elves can side apparate with people like Dobby did a little later in Deathly Hallows. So why wouldn't Regulus ask Kreacher to take them both back after they had switched the lockets? Or why didn't he bring water with him since Kreacher had told him what happens when you drink from the lake? He could have saved himself and destroyed the locket and Voldemort wouldn't know until he checked again which evidently didn't happen for many years. (I'm not exactly sure what year Regulus died but his mother was still alive). A: He ordered Kreacher to leave without him “And he order—Kreacher to leave—without him. And he told Kreacher—to go home—and never to tell my Mistress—what he had done—but to destroy— the first locket. And he drank—all the potion—and Kreacher swapped the lockets—and watched . . . as Master Regulus . . . was dragged beneath the water . . . and . . . “ —Harry Potter and the Deathly Hallows Kreacher, of course, as a house-elf enslaved to the Black family, was bound to obey. Of course, he could have disobeyed his orders on pain of being compelled to punish himself in the future, but he seemed to have a great deal of respect for Regulus, and therefore would not likely have disobeyed. As to why he specifically asked Kreacher to leave without him, we can only guess. The fact that he ordered Kreacher to leave without him suggests that he considered the possibility that Kreacher could leave with him. I can think of two possibilities: The potion would have eventually killed him. The potion may not have been immediately lethal, but it is possible that without drinking water immediately, the potion would be fatal. It seems unlikely he would have known this, though. If anything, Kreacher's example would suggest to him that the potion wasn't lethal. Perhaps he felt certain that Voldemort would hunt him down and kill him. He could never return to the Death Eaters, for fear that Voldemort would use Legilimancy to see what was in his mind. If he defected, Voldemort would kill him quickly anyway. Perhaps he preferred an immediate death to being hunted down by Voldemort. Ultimately, neither of these explanations is entirely satisfactory. The second makes more sense, but requires Regulus to be fairly resigned or suicidal. As an answer to your second question: Bringing water probably wouldn't have worked Harry tried to conjure water after Dumbledore drank the potion, but he failed: Aguamenti!” he shouted, jabbing the goblet with his wand. The goblet filled with clear water; Harry dropped to his knees beside Dumbledore, raised his head, and brought the glass to his lips — but it was empty. Dumbledore groaned and began to pant. “But I had some — wait — Aguamenti!” said Harry again, pointing his wand at the goblet. Once more, for a second, clear water gleamed within it, but as he approached Dumbledore’s mouth, the water vanished again. “Sir, I’m trying, I’m trying!” said Harry desperately, but he did not think that Dumbledore could hear him; he had rolled onto his side and was drawing great, rattling breaths that sounded agonizing. “Aguamenti — Aguamenti — AGUAMENTI!” The goblet filled and emptied once more. And now Dumbledore’s breathing was fading. His brain whirling in panic, Harry knew, instinctively, the only way left to get water, because Voldemort had planned it so... —Harry Potter and the Half-Blood Prince Clearly Voldemort had made plans, in order to leave a potential intruder with no other option than to drink from the lake and be dragged down by the Inferi. Presumably this would have extended to more mundane attempts to bring water into the cave, or to drink water therein. A: I think that the most likely explanation is that Regulus knew he could never escape Voldemort if he got out of the cave and ran for it (it says a couple times in the books that it's impossible to run away from Voldemort, look at Karakroff). He knew that if Voldemort caught up with him, he would for sure find out what Regulus did, either using torture or Legilimancy. For that same reason, Regulus couldn't go back to Voldemort and pretend nothing happenned, and we know that Death Eater can't just quit: they serve Voldemort or die. So basically, Regulus knew he had to die if they were to stand a chance of destroying the horcrux and rendering Voldemort mortal once more. There was no way around it.
{ "pile_set_name": "StackExchange" }
Q: Method to add predefined database into user's phone when app is installed Is there a method to add predefined SQLite database into user's phone when the app is first installed Thank you A: I think you have a few options here depending on the database size. If it's not really big, you can create it on the first run, and initialize it from the code with the insert method. If it's decent, you could attach it to the APK. If it's really big, the previous method would make your APK weight a lot, in this case, I would suggest you download it on the first run.
{ "pile_set_name": "StackExchange" }
Q: How to get the document loaded to WebView? I want to do this Uri targetUri = new Uri(Address.Text); WebView1.Navigate(targetUri); string content = WebView1.GetDocument(); //How can I get the document loaded from the target Uri? I have looked at the API in MSDN, but I didn't see anything noteworthy. I suppose I can hook into FrameNavigationStarting, and capture the Uri and initiate a separate request via WebClient, but this seems like a cludgy solution to a simple problem. I must be missing something - please help. A: Windows 8: You can get the WebView page content doing something like this: private void webView_LoadCompleted_1(object sender, NavigationEventArgs e) { WebView webView = sender as WebView; string html = webView.InvokeScript( "eval", new string[] {"document.documentElement.outerHTML;"}); // Here you can parse html .... } Windows 10 Update: InvokeScript() throws the following exception in Windows 10: An exception of type 'System.NotImplementedException' occurred in App1.exe but was not handled in user code Additional information: The method or operation is not implemented. Use InvokeScriptAsync() instead. XAML: <WebView Source="http://kiewic.com" LoadCompleted="WebView_LoadCompleted"></WebView> C#: private async void WebView_LoadCompleted(object sender, NavigationEventArgs e) { WebView webView = sender as WebView; string html = await webView.InvokeScriptAsync( "eval", new string[] { "document.documentElement.outerHTML;" }); // TODO: Do something with the html ... System.Diagnostics.Debug.WriteLine(html); }
{ "pile_set_name": "StackExchange" }
Q: How can I get source maps to work when running tests using ember-qunit for an ember app built on ember-cli I have an Ember app built using ember-cli and I'm writing my tests using the ember-qunit testing adapter and running them in the browser using testem as instructed in the ember-cli documentation. Although debugging in Google Chrome works fine when I'm interesting with my app, I am unable to use many debugging features such as breakpoints when running my tests. I often run into a problem that my tests fail despite my actual app seeming to work properly, and to investigate the problem I would like to step through code while my tests are running. But when I step into code that appears in vendor.js I just just see the following contents in my vendor.js: // Please wait a bit. // Compiled script is not shown while source map is being loaded! These two lines are lines 6 & 7 of the file. The lines before this are blank, and these two lines are the last lines in the file. The debugger has the first line of the file highlighted as if that's the current location in the source, but it cannot show the source for some reason. I can proceed to step through the code, but I can't see anything. However, if I find vendor.js in the list of sources in the developer tools sources file list then it opens as a separate source tab and I can see all my code. At this point I have two tabs labeled vendor.js, one with all my vendor assets and one with just those line quoted above. I am guessing that there is something different between how my tests are served and how my app is served in the development environment that is confusing Chrome. I am using the following versions of things: ember 1.9.1 ember-data 1.0.0-beta.14.1 ember-cli 0.1.9 qunit 1.17.1 ember-qunit 0.2.0 testem 0.6.33 Although I've poked around a bunch I don't really have any leads on where the problem is stemming from. Perhaps it's related to how testem is running the tests? Or could it be something that gets included in my tests has a messed up source map? I appreciate any help or ideas. A: I'm on ember-cli 0.2.2. I ran across this problem as well and found this Chrome issue with processing sourcemaps. People commenting on the issue suggest using the Chrome Canary build for now: I'm currently using the Canary build to put breakpoints in and debug my ember code. Get it here: https://www.google.com/chrome/browser/canary.html
{ "pile_set_name": "StackExchange" }
Q: Passing <5V through bus of tri-state transceiver I am following a schematic which implements a basic 8-bit register. The schematic is pictured below: According to the datasheet of the 74LS173 chip, The high-level output voltage is 2.4V with testing conditions assuming the minimum input voltage (although my case Vcc is 5V). The current configuration is set to output ~2.4V at each output pin on the 74LS173. I can confirm that the output is indeed ~2.4V. It appears that this chip is functioning perfectly well. The chip receiving this 2.4V potential is the SN74HC245. This chip is also fed 5V Vcc. The datasheet only states two input states (high + low) high being >3.15V at 4.5V Vcc and low being <1.35V at 4.5V Vcc. It is wired such that Ax is the input and Bx is the output. When I provide 5V to an input, I have 5V present at the cooresponding output. This is as we would expect. However, I need the 2.4V from the 74LS173 output to be present at the output of the 74LS245. In my head, I assume that I cannot simply pass 2V from the input of the transceiver since this is neither high or low. However, in the above schematic 2V is present in his outputs of the transceiver. This is demonstrated here: https://youtu.be/9WE3Obdjtv0?t=193 In my testing, when 2.4V is present at any A input, it does not exist at the corresponding B output. Whereas the same test with 5V input is indeed present at the output. In the datasheet for the SN74HC245 it appears that lowering the supply voltage lowers the minimum high-level input voltage, but in his case this was not necessary. How is this possible? A: It is not entirely clear what you are asking here, or what you say happens. Sometimes things outside the limits of the data sheet will work - or at least seem to for a while. The output voltage of your 74LS173 is so low because you are heavily loading it with the LEDs, and because LS logic doesn't have all that strong output drive to begin with. The best solution would be to use a CMOS inverter to drive the LED cathodes instead of the anodes, and to isolate driving them from other consumers of the logic signals being displayed. But you could substantially improve the situation without changing the topology by using a 74HC173 or 74HCT173 which will drive much closer to the rail even when loaded, and/or by enlarging the LED resistors so they draw less current. With regard to the 74xx245, if you use specifically 74HCT245 (note the "T") that has an input high threshold of 2 volts or less, even when powered at 5v. As such, it has a good chance of helping you by doing what all digital logic is designed to: restore the "noise margins" by taking any acceptable input, and turning it into a definitive output as close to the rail as its output structure can accomplish against a given load.
{ "pile_set_name": "StackExchange" }
Q: Generics/Parameterised classes Java Namespace G'day! Given two classes: A and B, and given G: a generic class, in Java. If I were to define the generic class as G<A> or G<B>, would it be make any difference that A and B are defined as classes themselves? My gut feel is no, because the letter is just the parameter to be used within the class attributes/methods, and will be replaced by whatever class G is parameterised by, upon initialisation. But this does seem to complicate things, because what if you wanted to have an attribute of type A or B within G? A: Generic type variables, like any other variables, have scope. Their scope is the body of the class they are declared in. Within that class, the name they were defined with always refers to the generic type. If you have another type of the same name declared elsewhere, you'll need to use its fully qualified name. class Generic<Integer> { Integer ourTypeVariable; java.lang.Integer realInteger; } Don't code like this, especially for common type names (everything in the JDK basically).
{ "pile_set_name": "StackExchange" }
Q: int and float in function overloading I have two overloaded function like below: void print(int i) { ... } void print(float f) { ... } Its giving me this error for print(1.2);: error: call of overloaded 'print(double)' is ambiguous Can anyone explain me why? A: 1.2 is a double literal not a float. So the compiler requires an explicit disambiguation. 1.2f would work as that is a float literal.
{ "pile_set_name": "StackExchange" }
Q: scanf doesn't store proper information in structure I have a problem with scanf. scanf doesn't store proper information in structure. Part of code is: if( figure->pro.p_category == 'C' || figure->pro.p_category == 'c' ){ printf("Enter data line> "); result += scanf("%s %d%c %d %d %d%c", (figure->pro.name), &temp,\ &figure->pro.money, &figure->exp.month, &figure->exp.year,\ &figure->ais.aisle_num, &figure->ais.aisle_side); if ( figure->pro.money == 'C') figure->pro.cents = temp; else if( figure->pro.money == 'D') figure->pro.dollars = temp; } figure->pro.name and figure->exp.month store different values. My structures are: typedef struct { char name[20]; char p_category, sub_p_category, money; int cents, dollars; }product_t; typedef struct { int aisle_num; char aisle_side; }aisle_t; typedef struct { int day, month, year; }experiment_t; typedef struct { int day, month, year; }packaging_t; typedef union { product_t pro; experiment_t exp; packaging_t pack; aisle_t ais; }figure_t; For instance; input> corn 89C 11 2010 11B This piece of code from output function: printf("The %s costs %d cents, expires in ",my_figure.pro.name, my_figure.pro.cents); print_exp_month(my_figure); printf("of %d, and is displayed in %d%c", my_figure.exp.year, my_figure.ais.aisle_num,\ my_figure.ais.aisle_side); its output: The costs 89 Dollar, expires in of 2000, and is displayed in 12B The proper output: The corn costs 89 cents, expires in November of 2000, and is displayed in 12B A: If you store your data in a union typedef union { product_t pro; experiment_t exp; packaging_t pack; aisle_t ais; } figure_t; only one set of data is stored at each time. When you read into, for example, figure->pro.money and figure->exp.month the data will be stored in the same place and overwrite each other. So when you try to print it, it is not there anymore!
{ "pile_set_name": "StackExchange" }
Q: Why would a git branch shared with two committers have many commits twice? (possible interaction with git-svn) When I setup my branch I did: git svn rebase git checkout -b branch-a Then I pushed that branch to the remote git repository and a colleague and I did work on it using git commit, git pull and git push. Now, I wanted to pull in all the new changes from subversion so I did: git checkout master git svn rebase git checkout branch-a git rebase master At this point I'm confused. What appeared to happen was that git would get to a commit with 1 or more conflicts and force me to resolve them. However, what the conflicts appeared to be was git having HEAD point to the tip of the tree (with the very latest code) and then attempting to apply every change one by one on top as if it were applying them to the original branch point. It felt like I was re-writing all the code again and most of the resolution was to keep the HEAD chunk and get rid of the commit chunk. My expectation was that the git rebase master command would start at the commit before the branch, add every commit from master and then add every commit on the branch. This would then yield a tip on the branch almost identical to what it was before the rebase. So, can anybody explain what I'm failing to understand. Failing that, can anybody suggest how to find out why git is deciding to do that. What would I be looking for in a git log to see why it was doing that. Edit: 2012-03-06 Further research has shown that we seem to have multiple copies of a couple of commits in our branch and a branch structure, from git log --graph which shows multiple branches when we thought there was only one. A snippet (identifying details removed and commit messages have been replaced with message-n. Message-n refers to identical messages): | * | commit f5c48df66ed9d733364562d8f125866aa6483c1e | | | Author: commiter-b | | | Date: Mon Feb 27 16:18:05 2012 -0800 | | | | | | Message-4 | | | | * | commit e6115229e629c237b08d0b2e149353f33ff66bd1 | | | Author: commiter-a | | | Date: Mon Feb 27 15:49:02 2012 -0800 | | | | | | Message-3 | | | | * | commit f85981736c59231dc34a7cef4fceab5cffdbdff2 | |/ Author: committer-a | | Date: Mon Feb 27 14:20:56 2012 -0800 | | | | Message-2 | | | * commit b09ba82e6290f5905d4c98fdcfbe2220d221e762 | Author: committer-a | Date: Mon Feb 27 14:04:13 2012 -0800 | | Message-1 | * commit 4d2892c239acfab5c9845518fde98ba551f273e6 | Author: committer-a | Date: Mon Mar 5 09:13:19 2012 -0800 | | UN-3710 Fixes after merge from svn ---8<----- snip * commit 8307d1ae8214ebe3eac5bdc5b835c21f89d727bd | Author: committer-b | Date: Mon Feb 27 16:18:05 2012 -0800 | | Message-4 | * commit 859acc56de59877cb721914443c63ad97882cb41 | Author: committer-a | Date: Mon Feb 27 15:49:02 2012 -0800 | | Message-3 | * commit 93e15921d735333194970cefc673a8b953e80838 | Author: committer-a | Date: Mon Feb 27 14:20:56 2012 -0800 | | Message-2 | * commit 7a863bb44be5c5019a0e0958460324dc3cfb2e6b Author: committer-a Date: Mon Feb 27 14:04:13 2012 -0800 Message-1 Our git workflow is conservative, I believe. We use git-svn to maintain master which is pushed to a remote git repository. We branch master and two or more committers work on it using git pull origin branch-a and git push origin. Now that we've noticed this feature of the problem we will be carefully watching in future for what event proximately causes it. A: First off, a quick summary of what git rebase does. If you have history that looks like this: trunk branch | / B C | / |/ A | | And you git rebase trunk when you're on branch, here's what you get: trunk/branch | C | B | A | | That's why it's called a rebase - the previous base of branch was commit A - that's the point at which it diverged from its "upstream" branch, trunk. After the operation, the new base is B, the newer HEAD of trunk. You have re-based it. git svn rebase just does this automatically, transplanting the changes you've made onto the new commits coming in from SVN. Now, there is one gotcha. git-svn, for hysterical raisins, doesn't use git notes to store its metadata. Instead, it rewrites the commit objects themselves, adding git-svn-id lines to the end of each commit message. This causes the SHA1 identifiers of each commit to change. So, even identical commits are different - and may conflict with alternate-universe versions of themselves! This is likely what you're seeing when you attempt to git rebase master from branch-a: branch-a diverged from some non-committed-to-SVN version of a previous state of master, so now when you attempt to merge, you'll get conflicts between the things changed on both sides. This is a limitation of git-svn: once you push a change to SVN, you must be careful to only use the pushed-to-SVN rewritten version of the commit. You can't mix the pre-committed and post-committed forms, because they're "different" changes with the same contents. You may verify this is what you're attempting to do by examining the changes from git merge-base master branch-a to master and branch-a. You'll likely see the same change on both sides. To get yourself out of the rut in this particular case, delete your branch, create a fresh one from master, then git cherry-pick the changes from branch-a in order, omitting the ones which master already contains. In the future, be more careful about using the not-yet-in-SVN revisions...
{ "pile_set_name": "StackExchange" }
Q: Creating a random name generator. How do I accomplish this? I'm trying to grab a single item from each of the Lists here, and combine them to make a unique name. This is just for kicks. :) Here are the lists: List<string> FirstNames = new List<string>() { "Sergio", "Daniel", "Carolina", "David", "Reina", "Saul", "Bernard", "Danny", "Dimas", "Yuri", "Ivan", "Laura" }; List<string> LastNamesA = new List<string>() { "Tapia", "Gutierrez", "Rueda", "Galviz", "Yuli", "Rivera", "Mamami", "Saucedo", "Dominguez", "Escobar", "Martin", "Crespo" }; List<string> LastNamesB = new List<string>() { "Johnson", "Williams", "Jones", "Brown", "David", "Miller", "Wilson", "Anderson", "Thomas", "Jackson", "White", "Robinson" }; I know I get a single item via an index, and I also know that I can use the Random class to generate a random number from 0 to ListFoo.Count. What I don't know is how to check if a random permutation has already been drawn from the collections. I've thought about using the tuple class: List<Tuple<int,int,int>> permutations = new List<Tuple<int,int,int>>(); But I'm having a brainfart here. ;) Any guidance? I'm not really looking for the entire code to this simple problem, just a suggestion or hint. EDIT Thanks to the suggestions given here, here what I've come up with. Any room for improvements? static void Main(string[] args) { List<string> FirstNames = new List<string>() { "Sergio", "Daniel", "Carolina", "David", "Reina", "Saul", "Bernard", "Danny", "Dimas", "Yuri", "Ivan", "Laura" }; List<string> LastNamesA = new List<string>() { "Tapia", "Gutierrez", "Rueda", "Galviz", "Yuli", "Rivera", "Mamami", "Saucedo", "Dominguez", "Escobar", "Martin", "Crespo" }; List<string> LastNamesB = new List<string>() { "Johnson", "Williams", "Jones", "Brown", "David", "Miller", "Wilson", "Anderson", "Thomas", "Jackson", "White", "Robinson" }; var permutations = new List<Tuple<int, int, int>>(); List<string> generatedNames = new List<string>(); Random random = new Random(); int a, b, c; //We want to generate 500 names. while (permutations.Count < 500) { a = random.Next(0, FirstNames.Count); b = random.Next(0, FirstNames.Count); c = random.Next(0, FirstNames.Count); Tuple<int, int, int> tuple = new Tuple<int, int, int>(a, b, c); if (!permutations.Contains(tuple)) { permutations.Add(tuple); } } foreach (var tuple in permutations) { generatedNames.Add(string.Format("{0} {1} {2}", FirstNames[tuple.Item1], LastNamesA[tuple.Item2], LastNamesB[tuple.Item3]) ); } foreach (var n in generatedNames) { Console.WriteLine(n); } Console.ReadKey(); } A: You are on the right track! Every time you generate a name, add it to your tuple list //Create the tuple Tuple <int, int, int> tuple = new Tuple<int, int, int>(index1, index2, index3) if(!permutations.Contains(tuple)) { permutations.Add(tuple); //Do something else }
{ "pile_set_name": "StackExchange" }
Q: Don't Want Include Tag's Stylesheet to Mix With Current Page's I have an include tag in dashboard.jade to include my header.jade file, but the header.jade file has its own stylesheet and when I run it, dashboard.jade's stylesheet also applies to the included header.jade. Is there a way to have dashboard.jade's stylesheet to apply only to it and not the included header.jade? Here's my code for dashboard.jade: doctype html html head title Todo List | &#x9; | link(rel='stylesheet', type='text/css', href='assets/css/todos.css') | &#x9; | link(href='https://fonts.googleapis.com/css?family=Roboto:400,700,500', rel='stylesheet', type='text/css') | &#x9; | link(rel='stylesheet', type='text/css', href=' https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.css') | &#x9; | link(rel='stylesheet', href='//cdnjs.cloudflare.com/ajax/libs/lemonade/2.1.0/lemonade.min.css') | &#x9; | script(type='text/javascript', src='assets/plugins/jquery-3.0.0.min.js') | | body include partials/header And here's my code for header.jade: doctype html html head title Eisenhower Productivity Tool // Meta meta(charset='utf-8') | meta(http-equiv='X-UA-Compatible', content='IE=edge') | meta(name='viewport', content='width=device-width, initial-scale=1.0') | meta(name='description', content='') | meta(name='author', content='') | | link(rel='shortcut icon', href='../favicon.ico') | | link(href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800', rel='stylesheet', type='text/css') // Global CSS link(href='../assets/plugins/bootstrap/css/bootstrap.min.css', rel='stylesheet') // Plugins CSS link(rel='stylesheet', href='../assets/plugins/font-awesome/css/font-awesome.css') // Theme CSS link#theme-style(rel='stylesheet', href='assets/css/styles.css') Any help is greatly appreciate, thanks! A: To use different CSS-Stylesheets I recommend to use a layoutbased enviroment with typical Jade/Pug block statements. This is how a layoutbased folder structur can look like: |--./ |-- |--jade |-- |-- |-- layouts |-- |-- |-- |-- mylayout.jade |-- |-- |-- template_1.jade |-- |-- |-- template_2.jade This could be your layout file mylayout.jade: doctype html block vars // Some default variables html head block head // default head for title and meta block defaultCSS // default css link(rel='stylesheet', type='text/css', href='path/to/default_style.css') style. body {} block additionalCSS body block body // default html in body block footer block defaultJS script. var someDefaltJavaScript = 'awsome" And here the template files template_1.jade: extends layout/mylayout.pug block head // this overrides the default "block head" from the layout // So put your special meta for your page here block additionalCSS link(rel='stylesheet', type='text/css', href='path/to/other_style.css') block body .this .is #where .your.content.goes template_2.jade: extends layout/mylayout.pug block head // this overrides the default "block head" from the layout // So put your special meta for your page here //- We dont use the "block additionalCSS" because we dont need it in this template block body .this .is #where .your.content.goes Beware to compile only the templatefiles, here is some other example: http://jade-lang.com/reference/extends/. You can also take a look into this small jade app of mine on github: https://github.com/pure180/gulp-pug-inheritance-test/tree/master/app
{ "pile_set_name": "StackExchange" }
Q: Can I push a modal view controller from within another modal view controller? I've got a rootViewController that, at one point, displays a peoplePickerNavigationController. I'm trying to push a second view controller when my user selects a specific contact property, like so: -(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)picker shouldContinueAfterSelectingPerson:(ABPersonRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier { RuleBuilder *ruleBuilder = [[RuleBuilder alloc] initWithNibName:@"RuleBuilder" bundle:nil]; [self pushModalViewController:ruleBuilder animated:YES]; [ruleBuilder release]; return NO; } This compiles just fine, but when I run the code in the simulator and run through the peoplePicker, nothing happens when I select a contact property. On a whim, I added a [self dismissModalViewControllerAnimated:YES]; just before [ruleBuilder release]; and that dismisses the peoplePicker, but otherwise has no effect on my missing ruleBuilder. Any ideas? A: Found the solution: [picker pushModalViewController:ruleBuilder animated:YES];
{ "pile_set_name": "StackExchange" }
Q: React Error: Each child in a list should have a unique key prop What's wrong with the following: <List> {sections.map(section => ( <> {section.header && <ListSubheader key={section.header}>{section.header}</ListSubheader>} {section.items .filter(item => new RegExp(itemsFilter, 'i').test(item.value)) .map(item => { const labelId = `multi-select-filter-list-checkbox-label-${item.key}`; return ( <ListItem key={item.key} role={undefined} dense button onClick={handleToggle(item)}> <ListItemIcon> <Checkbox className={checkboxClasses.root} edge="start" checked={checked.indexOf(item) !== -1} tabIndex={-1} disableRipple color="primary" inputProps={{ 'aria-labelledby': labelId }} /> </ListItemIcon> <ListItemText id={labelId} primary={item.value} primaryTypographyProps={{ variant: 'body1' }} /> </ListItem> ); }) } </> ))} </List> I believe I'm providing the keys; where is the error? A: The key prop should be provided for the wrapping tag. Replace <> with <React.Fragment> and apply a key to it. <React.Fragment key={section.header}>
{ "pile_set_name": "StackExchange" }
Q: Inline text formatting options with output to grid graphics object in R I am using ggplot/R for report generation and want more fine-grained control over text formatting. It's trivial to write some text, apply global formatting parameters, and output to a grid-graphics compatible object - just use textGrob. t <- textGrob( label = "SOME TEXT" ,gp=gpar(fontsize=20, col="grey") ) print(arrangeGrob(t)) Problem is that those formatting options only apply to the entire text string. What I'm looking for is something that would offer basic inline formatting options (font size, bold, italic, etc) - ideally something lightweight like Markdown/CSS/HTML. If I have to learn LaTeX, so be it, but that seems like overkill for what I'm trying to accomplish here. Any thoughts? A: You can use a "text cursor" alongside grid's functions for interrogating grobs. Say you had the phrase: "I want this text bold!!!!!!!, and you want the exclamation points in red: grid.text("I want ", name="notboldtext", hjust=0) text.cursor<-convertWidth(grobWidth("notboldtext") # Adds textGrob width & to location + unit(.5, "npc"), "npc") grid.text("this text bold", x=text.cursor, gp=gpar(fontface="bold"), name="boldedtext", hjust=0) text.cursor<- text.cursor + convertWidth(grobWidth("boldedtext"), "npc") grid.text("!!!!!!!", gp=gpar(col="red"), x=text.cursor, name="maptextnat", hjust=0)
{ "pile_set_name": "StackExchange" }
Q: How do I run multiple terminals in vps I have 2 flask restful API's . On my localhost, I open up a terminal and run uwsgi --ini /path-to-ini-file1. For 2nd API, I open up yet agan a new terminal and run uwsgi --ini /path-to-ini-file2. In VPS, I have only a single ssh window. How do I run those 2 on terminals in vps using ssh. Should I create a bin/bash script to achieve that? Any suggestion would be appreciated, thank you. A: To run commands in background and do not have them attach to the terminal you need to use something like: nohup uwsgi --ini /path-to-ini-file1 >out1.log 2>err1.log& nohup uwsgi --ini /path-to-ini-file2 >out2.log 2>err2.log& And you can run as many as need servers (limited by RAM and processor power). And after you logour from the server you will have them run
{ "pile_set_name": "StackExchange" }
Q: PHPExcel: How to Set an a Sheet's Paper Size with a User-Defined Paper Size? By using $objPHPExcel->getActiveSheet() ->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4); we can set a sheet's page size, but how do you supply a custom Paper Size for this? I want to set it to 8.5' x 13.0', Letter is 8.5 x 11.0 while Legal is 8.5 x 14.0 A: Check the source code for the library you're using at http://www.grad.clemson.edu/assets/php/phpexcel/documentation/api/__filesource/fsource_phpexcel_worksheet__phpexcelworksheetpagesetup.php.html#a118 Line of interest is this one in the comments. * 14 = Folio paper (8.5 in. by 13 in.) Which you can use: $objPHPExcel->getActiveSheet()-> getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_FOLIO); It doesn't seem like you can set custom sizes though, only the predefined ones.
{ "pile_set_name": "StackExchange" }
Q: Did Arnold Rimmer kill the Red Dwarf crew? In episode s01e06 'Me²' Rimmer's last moments alive are shown. Rimmer is being shouted at by the captain with a statement like 'It's your fault, you can't do sloppy work on the drive plate'. Moments later there's an explosion and they all die. I see an inference in this whereby Rimmer killed the crew due to his sloppy work. Is this correct? Is it ever confirmed? A: Yes. In the Pilot episode, titled The End, after Lister has woken from suspension he asks Holly how everyone died: LISTER: How? HOLLY: The drive plate was inefficiently repaired. It blew, and the entire crew was subjected to a lethal dose of cadmium 2 before I could seal the area. And then, when he gets to the drive room and starts trying to identify the piles of dust by taste, it is said: HOLLY: ... that's Second Technician Rimmer. LISTER: Oh, yeah? I didn't recognise him without his report book. What was Rimmer doing in the Drive Room? HOLLY: He was explaining to the Captain why he hadn't sealed the drive plate properly. The clear implication being that, yes, Rimmer was responsible for the deaths of the crew of the Jupiter Mining Corporation's Red Dwarf. What a smeg-head. A: No. In the episode "Justice" it was established in a court of law that although Rimmer was responsible for failing to re-secure the drive plate (the act that ultimately resulted in the deaths of the Red Dwarf's crew) that the ship's Captain and senior officers were themselves negligent in allowing him to have had that duty in the first place. JUSTICE: In the view of your counsel's eloquent defence, together with the reams of material evidence he submitted on computer card, this court accepts that, in your case, the mind-probe is not anadequate method of assessing guilt. It is not possible for you to have committed the crimes for which you blame yourself, and you may therefore go free. RIMMER: Objection! KRYTEN: Sir, what are you objecting to? RIMMER: I want an apology. The idea that a Technician: 2nd Class would be put in a position where he could destroy the ship is inherently laughable and speaks to either a design failure or a total lapse of command. Although he's physically responsible for the act, he bears no more moral responsibility for it than would a janitor who accidentally fell onto the nuclear launch button. A: Hollister sent a 2nd class technician (vending machine repairman specialization), the 2nd lowest ranked person on the ship to make a critical repair with no supervision from the people who were aboard who knew how to deal with those matters. Any court would consider the disaster to be Hollister's fault. You don't have to take my word for it though. In series 04 episode 03: Justice, Rimmer is literally put on trial because a Justice Computer scanned all their brains and found that Arnold felt guilt for killing all those people. Kryten "by lunch time" managed to hammer out a defense that clearly separated culpability from just a misplaced feeling of guilt. Kryten saves the day by proving no officer in their right mind would allow that man to endanger the entire crew. A beautiful closing statement. "This man is not guilty of manslaughter. He is only guilty of being Arnold J. Rimmer. That is his crime. It is also his punishment. The defense rests."
{ "pile_set_name": "StackExchange" }
Q: Selenium Python : NoSuchElementException I am trying to scrape images from Bing. I am using Selenium and trying to extract source links of the images. driver = webdriver.Firefox() driver.get("http://www.bing.com/images") elem = driver.find_element_by_id("sb_form_q") elem.clear() elem.send_keys("wheat zinc deficiency") elem.send_keys(Keys.RETURN) time.sleep(10) driver.find_element_by_class_name("mimg").click() driver.implicitly_wait(10) driver.find_element_by_xpath("/html/body/div[3]/div[2]/div[1]/div/span[1]/div/div/div/div[1]/span/span/img").click() The last line is showing error, which is selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element I have tried to avoid race condition by waiting for the page to load. I got the xpath using firebug add-on for firefox. A: Image opens in iframe, so to handle it you need to switch to that iframe first: driver.find_element_by_class_name("mimg").click() driver.switch_to_frame('OverlayIFrame') image = driver.find_element_by_xpath('//img[@class="mainImage accessible nofocus"]') print(image.get_attribute('src'))
{ "pile_set_name": "StackExchange" }
Q: How to remember the selected foo before and after a registration process? I have a view with 50 objects available for anonymous members. I the user clicks "Yes, i want to see more of this nice foo" he should register himself with only a email and/or password or even only a email is enough. Then a rule is needed to run and adds the role of member to the user. The member should now be returned to the selected foo/row. How to remember the selected foo before starting the registration process starts so I can redirect the user the foo correctly? Any suggestions great appreciation. A: I tried a lot of things with logintoboggan but the unauthenticaed role makes it diffecult for other modules to make well. So if you try to establish this with logintoboggan you are implicied chosing for modules which are only compatible with the adjustment of the login system. Something I do not prefer. I solved it with the following modules: Email_registration fo the username is not needed anymore GenPas for generating a auto password and direct login Persistent login for login in for a long time User email verification for verify the email nocurrent_pass for remove password edit’s profile email_confirm when user changes email When a anonymous gets on the site reqistrating is posssible with only email. With a rule you give the person a role. After that you can do what you like. If the person does not have a role yet and clicks on the link for premium content, you just append the unique id to the registration url and after registration a redirect can pick this up, the person is then verified with a first pre member role. You send all pre member roles an email with user email verification. If this is verified u can use a rule to upgrade the role. You now have a full registrated process without have the disadvanced of logintobboggan concept and in line with tha fact that no passwords are send by email.
{ "pile_set_name": "StackExchange" }
Q: DataImportHandler setup with PhpMyAdmin-MySQL I am trying to index a mysql database on phpmyadmin into solr. SOLVED BY @MatsLindh I have tried to find information necessary but no tutorials I have found deal with this setup. MY DATABASE: My mysql db is locally hosted and accessed through phpmyadmin. Here is the admin page. As you can see I have a db titled solrtest with table solr having fields id, date, Problem, and Solution. Now to link my db, the tutorials online were a bit inconsistent. The most consistent parts told me I would need to use solrs DataImportHandler and the mysql-connector-java. Another also mentioned a jdbc plug in. I have installed and put the .jar files here in my solr/dist directory. In some tutorials they have these also in the contrib folder but I have left in /dist. MY FILES: I have created a core titled solrhelp and made the following changes in the solhelp/conf files. solrconfig.xml <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="solr-dataimporthandler-7.5.0.jar" /> <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="solr-dataimporthandler-extras-7.5.0.jar" /> <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="mysql-connector-java-8.0.13.jar" /> <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="sqljdbc41.jar" /> <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="sqljdbc42.jar" /> <requestHandler name=" /dataimport" class=" org.apache.solr.handler.dataimport.DataImportHandler"> <lst name=" defaults"> <str name=" config">data-config.xml</str> </lst> </requestHandler> <requestHandler name " /dataimport" class=org.apache.solr.handler.dataimport.DataImportHandler"> <lst name="defaults"> <str name="name">solrhelp</str> <str name="driver">jdbc:mysql.jdbc.Driver</str> <str name="url">jdbc:mysql://localhost:8983/solrtest</str> <str name="user">root</str> <str name="password"></str> </lst> </requestHandler> the created data-config.xml <dataConfig> <dataSource type="JdbcDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:8983/solrtest" user="root" password=""/> <document> <entity name="solr" pk="id" query="select id, date, Problem, Solution from solr" > <field column="id" name="id"/> <field column="date" name="date"/> <field column="Problem" name="Problem"/> <field column="Solution" name="Solution"/> </entity> </document> </dataConfig> and the managed-schema.xml <field name="id" type="string" indexed="true" stored="true" multiValued="false" /> <field name="pdate" type="date" indexed="true" stored="true" multiValued="false" /> <field name="Problem" type="text_general" indexed="true" stored="true" /> <field name="Solution" type="text_general" indexed="true" stored="true" /> My question to the community is rather broad and I apologize. I want to know what all I am missing before I attempt to post this db. I dont think I have edited my files correctly and I dont really know of a way to test them before I attempt to post. It should be noted that in the dist folder I have two verions of the jdbc and have both in my solrconfig.xml file. Any direction to better tutorials or documentation would be appreciated. UPDATED FILES solrconfig <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="solr-dataimporthandler-7.5.0.jar" /> <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="solr-dataimporthandler-extras-7.5.0.jar" /> <lib dir="C:\Program Files\Solr\solr-7.5.0\contrib\dataimporthandler\lib" regex="mysql-connector-java-8.0.13.jar" /> <lib dir="C:\Program Files\Solr\solr-7.5.0\contrib\dataimporthandler\lib" regex="sqljdbc41.jar" /> <lib dir="C:\Program Files\Solr\solr-7.5.0\contrib\dataimporthandler\lib" regex="sqljdbc42.jar" /> <requestHandler name="/dataimport" class="org.apache.solr.handler.dataimport.DataImportHandler"> <lst name="defaults"> <str name="config">data-config.xml</str> </lst> </requestHandler> data-config <dataConfig> <dataSource type="JdbcDataSource" driver="com.mysql.cj.jdbc.Driver" url="jdbc:mysql://localhost:8983/solrtest/solr" user="root" password=""/> <document> <entity name="solr" pk="id" query="select * from solr" > <field column="id" name="id"/> <field column="date" name="date"/> <field column="Problem" name="Problem"/> <field column="Solution" name="Solution"/> </entity> </document> </dataConfig> A: THIS PROBLEM WAS SOLVED BY @MatsLindh My issue was configuration syntax. Below are the corrected data-config.xml and solrconfig.xml data-config <dataConfig> <dataSource type="JdbcDataSource" driver="com.mysql.cj.jdbc.Driver" url="jdbc:mysql://localhost:3306/solrtest" user="root" password=""/> <document> <entity name="solr" pk="id" query="select * from solr" > <field column="id" name="id"/> <field column="date" name="date"/> <field column="Problem" name="Problem"/> <field column="Solution" name="Solution"/> </entity> </document> </dataConfig> solrconfig <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="solr-dataimporthandler-7.5.0.jar" /> <lib dir="C:\Program Files\Solr\solr-7.5.0\dist\" regex="solr-dataimporthandler-extras-7.5.0.jar" /> <lib dir="C:\Program Files\Solr\solr-7.5.0\contrib\dataimporthandler\lib" regex="mysql-connector-java-8.0.13.jar" /> <lib dir="C:\Program Files\Solr\solr-7.5.0\contrib\dataimporthandler\lib" regex="sqljdbc41.jar" /> <lib dir="C:\Program Files\Solr\solr-7.5.0\contrib\dataimporthandler\lib" regex="sqljdbc42.jar" /> <requestHandler name="/dataimport" class="org.apache.solr.handler.dataimport.DataImportHandler"> <lst name="defaults"> <str name="config">data-config.xml</str> </lst> </requestHandler>
{ "pile_set_name": "StackExchange" }
Q: Upload progress in lighttpd no response I am trying to get the uploadprogress module for lighttpd 1.5 to work, but i am running into a strange problem: When i start the upload "/response" is getting called every second with the X-Progress-ID header set, but i am not getting any response. The GET call is just loading and loading but is getting no response. If call it manually (localhost/response?X-Progress-ID=someID) it appears to be right and the values for recieved and total are right and set. When i then cancel the upload progress (via the "X" Button in the Browser) /response keeps getting called, but now it will return with status 200, but, of course, with no right values set. Here is my code: Javascript: interval = null; function openProgressBar(uuid) { /* call the progress-updater every 1000ms */ interval = window.setInterval( function () { fetch(uuid); }, 1000 ); } function fetch(uuid) { req = new XMLHttpRequest(); req.open("GET", "/progress", 1); req.setRequestHeader("X-Progress-ID", uuid); req.onreadystatechange = function () { if (req.readyState == 4) { if (req.status == 200) { /* poor-man JSON parser */ var upload = eval(req.responseText); document.getElementById('tp').innerHTML = upload.state; /* change the width if the inner progress-bar */ if (upload.state == 'done' || upload.state == 'uploading') { bar = document.getElementById('progressbar'); w = 400 * upload.received / upload.size; bar.style.width = w + 'px'; } /* we are done, stop the interval */ if (upload.state == 'done') { window.clearTimeout(interval); } } } } req.send(null); } And my HTML: <form id="upload" enctype="multipart/form-data" action="index.php?X-Progress-ID={{tracking_id}}" method="post" onsubmit="openProgressBar('{{tracking_id}}'); return true;"> <input name="video" type="file" /> <input type="submit" class="button orange medium" value="Upload" /> </form> <div> <div id="progress"> <div id="progressbar"></div> </div> <div id="tp">(progress)</div> </div> EDIT: Forgot to mention...the {{tracking_id}} is getting generated in the php controller and printed with Twig. A: It seems to be a old bug with Chrome: https://code.google.com/p/chromium/issues/detail?id=45196 Same issue..tested it with Firefox and it worked fine. Sadly this bug does exist for like 2-3 years now, so there is no big hope for a fix in the near future. Got it working with uploading the file via XMLHTTPRequest.
{ "pile_set_name": "StackExchange" }
Q: Shortest two disjoint paths; two sources and two destinations We're given an unweighted undirected graph G = (V, E) where |V| <= 40,000 and |E| <= 106. We're also given four vertices a, b, a', b'. Is there a way to find two node-disjoint paths a -> a' and b -> b' such that the sum of their lengths is minimum?My first thought was to first find the shortest path a -> a', delete it from the graph, and then find the shortest path b -> b'. I don't think this greedy approach would work. Note: Throughout the application, a and b are fixed, while a' and b' change at each query, so a solution that uses precomputing in order to provide efficient querying would be preferable. Note also that only the minimum sum of lengths is needed, not the actual paths. Any help, ideas, or suggestions would be extremely appreciated. Thanks a lot in advance! A: This may be reduced to the shortest edge-disjoint paths problem: (Optionally) Collapse all chains in the graph into single edges. This produces a smaller weighted graph (if there are any chains in the original graph). Transform undirected graph into digraph by substituting each edge by a pair of directed edges. Split each node into the pair of nodes: one with only incoming edges of the original node, other with only its outgoing edges. Connect each pair of nodes with a single directed edge. (For example, node c in the diagram below should be split into c1 and c2; now every path containing node c in the original graph should pass through the edge c1 -> c2 in the transformed graph; here x and y represent all nodes in the graph except node c). Now if a = b or a' = b', you get exactly the same problem as in your previous question (which is Minimum-cost flow problem and may be solved by assigning flow capacity for each edge equal to 1, then searching for a minimum-cost flow between a and b with flow=2). If a != b, you just create a common source node and connect both a and b to it. If a' != b', do the same with a common destination node. But if a != b and a' != b', minimum-cost flow problem is not applicable. Instead this problem may be solved as Multi-commodity flow problem. My previous (incorrect) solution was to connect both pairs of (a, b) and (a', b') to common source/destination nodes, then to find a minimum-cost flow. Following graph is a counter-example for this approach:
{ "pile_set_name": "StackExchange" }
Q: Where are all the builtin macros defined in clang? I see that __GNUC__ is availble in clang, but they are not found here. Is there a place that has a complete list of all builtin macros in clang? https://clang.llvm.org/docs/LanguageExtensions.html A: Any macros defined by clang can be found with this command: clang -dM -E -x c /dev/null And any macros defined by clang++ can be found by this command: clang++ -dM -E -x c++ /dev/null Reference: this link
{ "pile_set_name": "StackExchange" }
Q: Can't import functions in java I'm having a problem importing from a java class. Here is my program: import MyStuff.*; public class Monday2 { public static void main(String[] args) { p("\n\n\n\t\tGood Morning from the Morning2 Class.\n\n\n"); } } Here is the MyStuff class: public class MyStuff { public static final void p(String inputString) { System.out.println(inputString); } } Please tell me what I am doing wrong A: You forgot magic word - static, after your import like this import static MyStuff.*; You can read more in appropriate topic. Hope it helps!
{ "pile_set_name": "StackExchange" }
Q: Align a fixed positioned element to center horizontally I have three components - a logo, #menuA and menuB. I would like the logo centrally aligned, menuA in the top left and menuB in the top right. The parent container #nav has position:fixed which appears to be causing me problems. I can get the logo roughly in the middle but it appears to be slightly to the right - I think because menuA is wider than menuB. This is what I have so far: Fiddle Demo #nav { position:fixed; height:30px; background:#FFF; padding:10px 20px; z-index:1; top:0; right:0; left:0; } #logo { position:fixed; left:50%; right:50%; font-family: 'Pacifico', cursive; font-size:28px; color:#333333; } #menuA { float:left; } #menuB { float:right; } and the HTML <div id="nav"> <div id="logo">Logo</div> <div class="ui basic buttons" id="menuA"> <a ui-sref="editor"><div class="ui button" style="padding-left:8px;padding-right:8px;"><i class="file outline icon" style="margin-right:0px;"></i>New</div></a> <div class="ui button" style="padding-left:8px;padding-right:8px;" ng-click="save()"><i class="add icon" style="margin-right:0px;"></i>Save</div> <div class="ui button" style="padding-left:8px;padding-right:8px;" ng-click="fork()"><i class="fork code icon" style="margin-right:0px;"></i>Fork</div> </div> <div class="ui selection dropdown" id="menuB"> <input type="hidden" name="gender"> <div class="default text">Language</div> <i class="dropdown icon"></i> <div class="menu"> <div class="item" data-value="0">Javascript</div> <div class="item" data-value="1">HTML</div> <div class="item" data-value="2">CSS</div> <div class="item" data-value="3">Python</div> </div> </div> <div style="clear"></div> </div> A: TRY THIS - DEMO If you give width (i.e 100px) to your logo, then it will solve your problem. CSS #nav { position:fixed; height:30px; background:#FFF; padding:10px 20px; z-index:1; top:0; right:0; left:0; } #logo { position:fixed; left:50%; font-family: 'Pacifico', cursive; font-size:28px; color:#333333; text-align: center; width: 100px; margin-left: -50px; } #menuA { float:left; } #menuB { float:right; }
{ "pile_set_name": "StackExchange" }
Q: Creating a choropleth (polygon) map with 2 dimensional values using ggplot I would like to create a choropleth map visualising 2 dimensional values (= color fill the polygons according to an ordered pair (v1, v2), where v1 and v2 are ordered factors). Here is an example of how the result should look like: I think the color matrix legend with the two dimensions makes it clear what I want to achieve. I would like to implement this using ggplot2::geom_polygon. Minimal example: ids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3")) values <- data.frame( id = ids, v1 = factor(c("Hi","Med","Med","Hi","Lo","Lo"), levels=c("Lo", "Med", "Hi"), ordered=TRUE), v2 = factor(c("Hi","Lo","Lo","Med","Med","Hi"), levels=c("Lo", "Med", "Hi"), ordered=TRUE)) positions <- data.frame( id = rep(ids, each = 4), x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3, 0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3), y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5, 2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2)) datapoly <- merge(values, positions, by=c("id")) I would like to combine the two following maps in just one following the example above. The color fill of the polgons should be according to the ordered pair (v1, v2) and of course I would need a color matrix legend. library("ggplot2") ggplot(datapoly, aes(x=x, y=y)) + geom_polygon(aes(fill=v1, group=id)) ggplot(datapoly, aes(x=x, y=y)) + geom_polygon(aes(fill=v2, group=id)) A: Bit late to the party here, but, for the benefit of anyone coming across this question later, https://github.com/wmurphyrd/colorplaner seems to do exactly what you want. The second example in the usage section even gives an example of coloring in a map.
{ "pile_set_name": "StackExchange" }
Q: SSMS express login failed I'm very new to SQL Server. I'm currently using SSMS 2005 Express and .Net Framework 4.6 and has this error when connecting to server. Can You please help me..TIA. A: SQL Server 2005 (and its SQL Server Management Studio) requires version 2.0 of the .NET Framework installed. A higher version of SSMS (i.e. 2008 R2) will connect to your SQL Server 2005 as well. SSMS 2008 R2 requires .NET Framework 3.5 SP1. If installing additional .NET Framework versions is not possible you could install the latest SSMS version 17.4 and connect to your SQL Server. It is a free download from Microsoft and requires .NET 4.6.1+ to run.
{ "pile_set_name": "StackExchange" }
Q: Does "Wild Shape" require the caster to have seen the elemental they are changing into? At 10th level, a Druid of the Circle of Moon gains the ability to take the form of 4 Elementals (fire, water, air, or earth). My question is: Does the Druid unlock access to these 4 elementals immediately or does he/she have to have seen an elemental to assume it's form? A: From the PHB page 66: Starting at 2nd level, you can use your action to magically assume the shape of a beast that you have seen before. And page 69: At 10th level, you can expend two uses of Wild Shape at the same time to transform into an air elemental, an earth elemental, a fire elemental, or a water elemental. It seems fairly clear that these are two distinct abilities, even if they share many of the same rules. The first allows you to take the form of "a beast that you have seen before", while the second lets you take the form of four specific creatures. There is no mention of needing to see those creatures before you turn into them. It should also be noted that this only allows you to turn into one of those four, specific elementals, not elementals in general. So you can't use Wild Shape to turn into, for example, an Azer or a Galeb Duhr. Finally, if your DM decides to rule that you need to see each of them to turn into them regardless, you can always cast Conjure Elemental four times to see each of them.
{ "pile_set_name": "StackExchange" }
Q: jquery resizable with absolute position I have following problem: I need to make my div re-sizable, but it needs to be located on right bottom of the page. When I use jquery resizable function and position: absolute, div jumps around... Sample Code: $('#resizable').resizable({ handles: { 'nw': '#nwgrip', 'n': '#ngrip', 'w': '#wgrip' } }); <div id='resizable'> <div id='content'> Im Resizable! </div> <!-- Define corners --> <div class="ui-resizable-handle ui-resizable-nw" id="nwgrip"></div> <div class="ui-resizable-handle ui-resizable-n" id="ngrip"></div> <div class="ui-resizable-handle ui-resizable-w" id="wgrip"></div> </div> A: The problem is that resizable uses top left with and height to set the element's position. Now yours is positioned with right and bottom at the beginning, so the moment the resizable updates the position, right will be deleted and left will be set. (to 0 because it doesn't exist). So you'll have to calculate the left position at page load or maybe on resize start
{ "pile_set_name": "StackExchange" }
Q: ggplot How to select values from two different colums? I have a .csv file which has 3 parameters for each item. If the item is "apple", the 3 values are: "Area harvested" "Yield" "Production" I don't know how to plot these Apple rows with only the "Production" value This is my code, but it plots the 3 values: library(tidyverse) library(dplyr) df <- read.csv("C:/Users/....data.csv", encoding = "ASCII", header = TRUE, sep = "," ) ggplot(subset(df, Item == "Chillies and peppers, green"), aes(x = Area, y = Y2014)) + geom_bar(stat = "identity", width = 0.6) + coord_flip() view(df) this is the .csv link to csv Thank you so much in advance! A: You can filter the data before calling ggplot, like this df %>% filter(Item == "Apples", Element == "Production") %>% ggplot() + geom_bar(aes(Area, Y2014), stat = "identity", width = 0.6) + coord_flip() NOTE: You can also sort the results for a better visualization using reorder(Area, Y2014, FUN = abs) instead of simply Area. df %>% filter(Item == "Apples", Element == "Production") %>% ggplot() + geom_bar(aes(reorder(Area, Y2014, FUN = abs), Y2014), stat = "identity", width = 0.6) + coord_flip()
{ "pile_set_name": "StackExchange" }
Q: Is it possible to navigate a site by clicking links and then downloading the correct piece? I'll try to explain what exactly I mean. I'm working on a program and I'm trying to download a bunch of images automatically from this site. Namely, I want to download the big square icons from the page you get when you click on a hero name there, for example on the Darius page the image in the top left with the name DariusSquare.png and save that into a folder. Is this possible or am I asking too much from C#? Thank you very much! A: In general, everything is possible given enough time and money. In your case, you need very little of former and none of latter :) What you need to do can be described in following high-level steps: Get all <a> tags within the table with heroes. Use WebClient class to navigate to URL these <a> tags point to (i.e. to value of href attributes) and download the HTML You will need to find some wrapper element that is present on each page with hero and that contains his image. Then, you should be able to get to the image src attribute and download it. Alternatively, perhaps each image has an common ID you can use? I don't think anyone will provide you with an exact code that will perform these steps for you. Instead, you need to do some research of your own.
{ "pile_set_name": "StackExchange" }
Q: How to change view automatically without any action in ionic? I like to skip first page automatically in 2 seconds on my App . Do I add code in js or html? please, help me. Thank you A: Assuming your tabs (and states) are named 'tab1', 'tab2', ... and your app module is myApp, you can add in your controller this code: myApp.controller('myController', function($scope, $state, $timeout) { $timeout(function () { $state.go('tab2'); }, 2000); ... });
{ "pile_set_name": "StackExchange" }
Q: I want to access .sql file format on the computer without using the internet I need to access data from the database and manipulate the data. I can do this through the internet, however I need to make it so that the data can be accessed on the computer that the program runs without having internet connection. The current method I'm using is displayed below with the code: Dim dbDataSet2 As New DataTable Sqlconn = New MySqlConnection Sqlconn.ConnectionString="server=xx.xx.xx;userid=root;password=xxxxxx;database=xxxxxx" Dim SDA As New MySqlDataAdapter Dim bSource As New BindingSource Try Sqlconn.Open() 'open connection Dim query As String query = "SELECT * FROM bbs_test.test" command = New MySqlCommand(query, Sqlconn) SDA.SelectCommand = command SDA.Fill(dbDataSet2) bSource.DataSource = dbDataSet2 DataGridView_array.DataSource = bSource SDA.Update(dbDataSet2) Sqlconn.Close() Catch ex As Exception MessageBox.Show(ex.ToString) End Try Is there a was to change this, so the file location is using a path like C: \ ...... or something similar Also the file gets updated as well from time to time and the format of the file is .sql Please can anyone help me Thank You A: The problem is likely the server address in the connection string. To make it connect to your local SQL Server engine, you can simply set the address to either (local) or ., for instance: Sqlconn.ConnectionString="server=.;userid=root;password=xxxxxx;database=xxxxxx"
{ "pile_set_name": "StackExchange" }
Q: Backbone Drop Event Not Working I have a dashboard with two backbone Views. One view contains a variety of drop zones, the other contains items that are draggable="true". However, these drop zones are not firing on drop events, yet they are firing on dragenter and dragleave. Why is the drop event not firing? Note: The template that is being rendered contains the .item-drop-zone div elements The View containing the Drop Zones: Shopperater.Views.ModuleMedleyView = Backbone.View.extend({ tagName: "div", className: "row", template: JST['modules/medley'], initialize: function() { _.bindAll(this); }, events: { 'dragenter .item-drop-zone' : 'highlightDropZone', 'dragleave .item-drop-zone' : 'unhighlightDropZone', 'drop .item-drop-zone' : 'dropTest' }, dropTest: function(e) { console.log("dropped!") }, highlightDropZone: function(e) { e.preventDefault(); $(e.currentTarget).addClass('item-drop-zone-highlight') }, unhighlightDropZone: function(e) { $(e.currentTarget).removeClass('item-drop-zone-highlight') }, render: function () { this.$el.html(this.template({ })); return this; } }); A: You have to tell the browser that the element is a drop target: events: { 'dragenter .item-drop-zone' : 'highlightDropZone', 'dragleave .item-drop-zone' : 'unhighlightDropZone', 'drop .item-drop-zone' : 'dropTest', 'dragover .item-drop-zone': function(ev) { ev.preventDefault(); } } See https://developer.mozilla.org/en-US/docs/DragDrop/Drag_Operations#droptargets for more information about drop targets. You need both dragenter and dragover events. Since you are already doing the dragenter, you can just add the dragover. From the link Calling the preventDefault method during both a dragenter and dragover event will indicate that a drop is allowed at that location.
{ "pile_set_name": "StackExchange" }
Q: Strange image result for UIBarButtonItem I want to add the following image to the UIBarButtonItem: However when I set it to the "Image" property of the UIBarButtonItem via Interface Builder in XCode 6 I got the following result: What am I doing wrong? How can I fix it? Thanks in advance. A: By default your images get tinted using the tint color and alpha mask. You can set it to render the original by calling [myBarButton setImage:[[self imageForState:UIControlStateNormal] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal]; on the button!
{ "pile_set_name": "StackExchange" }
Q: Using java to read/extract data and place in a var Hay Peeps, I have a question. I am trying to write part of a program. What I need it todo is read a document called marks.txt and then extract the data in the document and place it in variables so that I can calculate the total. the layout for the document is simply Assessment1 41 Assessment2 41 Assessment3 41 When the code is ran the variables that have been declared stay NULL Here is the code for that part of the program public void readMarks() { try { doc = new File ("marks.txt"); if(!doc.exists()) { System.out.println ("Marks.txt Does Not Exist"); } Scanner input = new Scanner(doc); while (input.hasNext()) { String Assessment1 = input.next(); int mark1 = input.nextInt(); String Assessment2 = input.next(); int mark2 = input.nextInt(); String Assessment3 = input.next(); int mark3 = input.nextInt(); } input.close(); } catch (FileNotFoundException ex) { System.err.println("File has not been found"); } } A: It is never a good idea to declare variables inside a loop. I have tried this solution and it works flawlessly, if you have any problem probably it is related with marks.txt being in an incorrect location public static void readMarks() { String Assessment1 = null, Assessment2 = null, Assessment3 = null; int mark1 = 0,mark2 = 0,mark3 = 0; try { File doc = new File ("marks.txt"); if(!doc.exists()) { System.out.println ("Marks.txt Does Not Exist"); } Scanner input = new Scanner(doc); while (input.hasNext()){ Assessment1 = input.next(); mark1 = input.nextInt(); Assessment2 = input.next(); mark2 = input.nextInt(); Assessment3 = input.next(); mark3 = input.nextInt(); } input.close(); System.out.println(Assessment1 + " "+mark1 + Assessment2 +mark2+ " " + Assessment3 +mark3+ " "); } catch (FileNotFoundException ex) { System.err.println("File has not been found"); } } If you have any doubt don't hesitate to ask
{ "pile_set_name": "StackExchange" }
Q: VSTS returns Bad Request, when specifying changeset for build I'm using VSTS for my Nightly/CI builds. VSTS pulls the code from TFS repository. I noticed that triggering the build against (specific changeset E.g.'33333', 'C33333') returns "BadRequest 400 The value specified for SourceVersion is not a valid version spec." Microsoft.TeamFoundation.Build.Server.BuildRequestValidationFailedException When changeset is not specified everything works fine. Did anyone had this problem? A: I have a request to Microsoft. They know about this bug. This issue will be fixed this week.
{ "pile_set_name": "StackExchange" }
Q: Vertical alignment with CSS Yeah, yeah, I know this is yet another question about vertical alignment with CSS and it's been done a million times before. Rest assured that I have come across this problem many times and I've already done the reading about various ways to centre vertically with CSS. I'm asking here because none of those ways do quite what I want to do, and I just want to make sure that my suspicion (that CSS vertical alignment is broken and will not do what I want it to do) is definitely correct. First up, here's my test case: http://www.game-point.net/misc/testAlign/ Here's the criteria: I want to align the 'centred text' vertically, with respect to the DIV containing the 'TestTestTest...' text. I don't want to specify ANY heights. I want both the 'TestTestTest' and the 'Centred text' DIVs to get their heights dynamically, according to the amount of text they have, and the width limit they have. I don't want to use Javascript. This seems to be impossible even in CSS3, let alone CSS2. The annoying thing is that I'm almost there; the position:absolute; top:-50%; DIV works to set the top of that DIV to halfway down the container DIV. The problem is that the inner DIV, with style position:relative; top:-50%; doesn't do anything to move the content up by half its height, to centre it fully, because CSS says that an absolutely positioned DIV doesn't have a height and therefore top:-50% is meaningless. As far as I can tell, this is just a fundamental flaw in CSS for no particular reason. An absolutely positioned element does have a height, and I don't know why CSS pretends it doesn't. I just wanted to ask whether anyone had any ideas as to how I could achieve the desired effect, pictured at the bottom, given the criteria I outlined above. Ironically IE6/7/8's 'broken' box model, in quirks mode, gives me this very effect. Shame they're 'fixing' it in IE9 so it won't anymore. A: OK, my suspicion was indeed correct and this is not possible (I think it's a flaw in CSS and they should provide a means of vertical alignment within a DIV without specifying inner element heights). The least bad solution I ended up with was this: specify the height of the 'middle' DIV - that is, the DIV which is displayed using position:absolute and contains the real content. I've added it to the test case page at http://www.game-point.net/misc/testAlign/ under the heading With line-height:100% and hardcoded 'middle' DIV height. This solution means that you must know the height of the content to be vertically centred in advance, which sucks because the browser calculates this and you shouldn't need to specify it, but it's the only way (until CSS gets its act together). I used ems to specify the height too, so that zooming text in and out doesn't ruin the vertical centring. Turns out that for the 2 lines of 'Centred text' I had, this height equates to exactly 2 ems (at least on my machine). If I were to change that content's height, or it were to change dynamically to say 3 lines or 1 line, the parent div's hardcoded em height would also have to change. So, here's the code I finally ended up with if anyone's interested: <div style="border:1px solid black; padding-left:60px; width:250px; position:relative; word-wrap:break-word;"> TestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTestTest <!-- Unfortunately, must set this DIV's height explicitly or the contained DIV's relative positioning won't work, as this DIV is considered to have NO implicit height --> <div style="position:absolute; display:block; top:50%; left:0px; height:2em;"> <div style="position:relative; top:-50%; background-color:#00aa00; line-height:100%;"> Centred text<br/> Centred text </div> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: What's the risk from enabling ptrace in docker? Solutions for various problems (e.g., here and here) suggest enabling SYS_PTRACE when running a container that, say, needs to run a debugger or a fuzzer. Given that the capability isn't enabled by default, there must be some security implications of granting it -- the official documentation gives a vague "could leak a lot of information on the host". Presumably this means it could allow information about the host to be leaked to the runtime environment of the container -- but what information? Are there any other security implications? A: There's some good detail on this topic, in this whitepaper. Essentially the problem is that allowing ptrace will allow the contained process to bypass any seccomp filter in place, allowing dangerous syscalls to be made. To quote the document CAP_SYS_PTRACE: The ability to useptrace(2)and recently introduced cross memory attach syscalls such as process_vm_readv(2)andprocess_vm_writev(2). If this capability is granted and the ptrace(2) syscall itself is not blocked by a seccomp filter(as discussed more in Section 8.3 on page74), this will allow an attacker to bypass other seccomp restrictions. Update - As mentioned below in comments from @forest the above only applies to versions of the kernel before 4.8, so modern Linuxes (possibly excepting RHEL/CENTOS 7 and earlier which are still around) shouldn't have this problem.
{ "pile_set_name": "StackExchange" }
Q: MYSQL - count(id) with 2 different clause in 1 query (with Inner Join, NOT GROUP BY) I have 2 tables (customer & orders) contains : // Customer Table customer_id customer_name customer_address 1 customer01 address01 2 customer02 address02 3 customer03 address03 4 customer04 address04 5 customer05 address05 // Orders Table order_id customer_id order_status 1 1 rejected 2 1 success 3 2 success 4 1 success 5 1 pending 6 2 success 7 2 pending 8 3 pending So, in the Order table I had : customer01 had 2 success, 1 rejected and 1 pending customer02 had 2 success and 1 pending customer03 only had 1 pending EXPECTATION : Result that I need customer_id Customer_name (success) order_status 1 customer01 (2) pending 2 customer02 (2) pending 3 customer03 (0) pending My Query : using sample data on SQLfiddle SELECT o.order_id, c.customer_id, CONCAT(c.customer_name, " (", (SELECT COUNT(order_id) FROM orders WHERE order_status = 'success'),")") as "Customer Name (success order)", o.order_status FROM customer c INNER JOIN orders o ON c.customer_id = o.customer_id WHERE o.order_status = 'pending' ORDER BY c.customer_id ASC; RESULT customer_id Customer_name (success) order_status 1 customer01 (4) pending 2 customer02 (4) pending 3 customer03 (4) pending EDIT : Remove SQL Fiddle. A: Missing link between subquery and main query to get the related count (SELECT COUNT(order_id) FROM orders WHERE order_status = 'success' and customer_id = c.customer_id --- you need to link the sub and the mainquery )
{ "pile_set_name": "StackExchange" }
Q: Is it possible for non-EU companies to avoid GDPR regulatory issues through filters and firewalls? Background Most internet feeds are unfiltered. Everyone who has ever rented or set up a server knows malicious traffic comes in from all over the world, including the European Union (but mostly from other places), as soon as a server is online, and passwords, keys, and/or facilities to firewall malicious traffic need to be ready beforehand. Scenario Small Town News USA Inc. (a fictional company) operates a newspaper and web site about Small Town, USA. Primary customers live in Small Town, USA. Recently, their corporate lawyer has suggested they need to pay several thousand dollars to do preparation and paperwork for European GDPR regulatory compliance that affects businesses worldwide with any EU citizen data. Management, thinking it would be less expensive to filter and inconvenience maybe 5-10 travelers and remote viewers who are accessing the website from Europe, decides that the easiest way to deal with GDPR liability is to reject internet traffic from non-USA viewers. Unfortunately, the commonly available technology to do this involves IP-sniffing. In more detail, a web server is designated as a "firewall/Nginx-reverse-proxy" and would take a connection , examine the IP address (personally identifiable information under GDPR; see FAQ What Constitutes Personal Data?) and then forward only USA connections to a different server containing the Small Town News web site. But "Rejected" connections are still processed by sending back a web page containing only: "Sorry, we can't serve you at your current location." IP addresses and times are recorded in the web server logs. Furthermore, IT staff want web server logs to include IP addresses so that they can ban malicious traffic. This involves automated processing of behavioral data and also storing bad-behavior IPs in other files that update the firewall data, which is held in an operating system table. It turns out the USA-only filter is an imperfect technological measure. It does not filter out 100% of EU-resident traffic. First, there is no perfect mapping of IP addresses to locations. For instance, an IP address apparently owned by the US Navy could be traffic coming from an EU-resident civilian contractor on his lunch hour who works at a US naval base in, e.g. Italy. An EU-resident visitor to the USA could still access the full website from the USA. Another EU-resident could buy VPN (Virtual Private Network) service to disguise their computer's true location, and that could involve forwarding their traffic from a point within the USA which would allow fetching the full Small Town News website because the Small Town News firewall received a USA IP address. Enforcement For those who think this is scaremongering and unenforceable, perhaps read: How the EU can fine US companies for violating GDPR which isn't entirely certain, but does suggest the possibility of US cooperation for collecting EU civil fines. Maybe Location-sniffing is also illegal... The article "Why the US and Other Non-European Companies Need to Comply with the GDPR" on busineessknowhow.com claims: "... identifying people within the EU and refusing them access to your site or service based on the geolocation of their IP address - is actually specifically prohibited by GDPR. GDPR contains a prohibition against 'profiling', which GDPR defines as "any form of automated processing of personal data consisting of the use of personal data to evaluate certain personal aspects relating to a natural person, in particular to analyze or predict aspects concerning that natural person's performance at work, economic situation, health, personal preferences, interests, reliability, behavior, LOCATION or movements." Since this doesn't cite specific sections of the 100+ page regulation, I don't know if it is correct. It all sounds like a great welfare project for lawyers, regulators, and IT pros who take the time to specialize in this area and bad for the creative entrepreneur who simply wants to put something online. Question Is Small Town News GDPR compliant under their (unfortunate) EU-blocking policy? Or can they only become compliant by outsourcing the filtering to some other company, who can be the scapegoat when filtering is imperfect? A: Yes, this is a viable option. And no, it doesn't need to be perfect. The use of such a filter is a technical means, but it also serves to communicate that Small Town News explicitly does not envisage to provide service to Europeans or others resident in the EU. If a user chooses to use a VPN to do visit Small Town News webpages, it's reasonable to expect that this would be comparable to buying the Small Town News paper in print while physically in the USA. It's a common principle that courts have to decide on jurisdiction, and actions of a party can factor in this decision. A: this technological measure does not filter out 100% of EU-resident traffic As a personal data processor not established in the EU, Small Town News will have to worry about data subjects in the EU only (Art. 3(2)): This Regulation applies to the processing of personal data of data subjects who are in the Union by a controller or processor not established in the Union That said, Small Town News will not have to care about GDPR when it comes to serving EU residents who are currently outside the EU. On the other hand, Small Town News will have to care about GDPR when anyone in the EU (residents as well as US or say Zimbabwean tourists) accesses the website: Notably, Article 3(2) applies to the processing of personal data of any individual “in the EU.” The individual’s nationality or residence is irrelevant. The GDPR protects the personal data of citizens, residents, tourists, and other persons visiting the EU. So long as an individual is in the EU, any personal information of that person collected by any controller or processor who meets the requirements of Article 3(2) is subject to the GDPR. Where Article 3(2) applies, controllers or processors must appoint an EU-based representative. From this point, Small Town News has two options (apart from complying with GDPR in full): Ban EU traffic by IP address so that people in the EU cannot access it. As you noted, geo IP mapping may not be accurate, so this will not provide 100% protection. Also, people in the EU could use VPN/proxy, which will not negate the fact that they are still in the EU and therefore you have to comply with GDPR when treating them; or Do not offer goods or services to people in the EU and do not monitor their behavior. Using a .us TLD, offering sales in US dollars only to people with a US address only and disabling any user analytics for non-US IP addresses should suffice.
{ "pile_set_name": "StackExchange" }
Q: Can I use SQFP package instead LQFP for PCB design in Proteus 8? I have to design sound card with CM108AH and its package is LQFP with 48 pins. I use Proteus 8 for designing but there is no LQFP package for PCB. Can I use SQFP 48 pins instead ? A: You can only substitute the footprint if it matches the footprint specifications for the part that you are using. It is up to you to look in the data sheet or other supplementary information provided by the manufacturer to find the suggested footprint specifications. If they do not match then you use the footprint design facilities of your CAD package to create a suitable new footprint. Any CAD package worth it's salt has this capability. If yours does not then find one that does.
{ "pile_set_name": "StackExchange" }
Q: Importing private key for watched address in bitcoind, rescan necessary? If I have a watch only address in my wallet and then I import the private key corresponding to it, will I need to do a rescan or will it automatically update my available balance with any UTXOs for that address (at least those created since I began watching it)? It seems to me like it shouldn't require a rescan but I'm wondering if anyone has actually done this successfully. If I don't get an answer here after a while I can test it out myself and report back. A: No additional rescan is required in that case. Though there is a little bug in Bitcoin-Qt: the balance will not get properly updated if you import a private keys where you already have a watch-only script. Bitcoind (listtransactions, getbalance, etc.) are not affected.
{ "pile_set_name": "StackExchange" }
Q: I'm developing asp .net Web API to use it in my Android app, I'm developing restful web service using asp.net Web API to use it in my Android app. and here what I get when I run my API [ { "id": 41, "firstName": "ahmed", "lastName": "jallad", "gender": "male", "salary": 6000, "img": "C:\\Users\\ahmed\\Desktop\\hi.png" }, { "id": 46, "firstName": "ali", "lastName": "ali", "gender": "male ", "salary": 5000, "img": "C:\\Users\\ahmed\\Desktop\\hi.png" }, { "id": 47, "firstName": "wael", "lastName": "wael", "gender": "male", "salary": 6000, "img": "C:\\Users\\ahmed\\Desktop\\hi.png" }, { "id": 48, "firstName": "sara", "lastName": "sara", "gender": "female", "salary": 5000, "img": "C:\\Users\\ahmed\\Desktop\\hi.png" }, { "id": 49, "firstName": null, "lastName": null, "gender": null, "salary": null, "img": "C:\\Users\\ahmed\\Desktop\\hi.png" } ] I'm storing the path of the image in SQL database, and here is .net code public HttpResponseMessage Get(string gender = "ALL") { using (EmployeeDBEntities entities = new EmployeeDBEntities()) { int a = 0; switch (gender.ToLower()) { case "all": return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.ToList()); case "male": return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.Where(e => e.Gender.ToLower() == "male").ToList()); case "female": return Request.CreateResponse(HttpStatusCode.OK, entities.Employees.Where(e => e.Gender.ToLower() == "female").ToList()); default: return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "value for gender must be Male, Femle or ALL. " + gender + " is not valid"); } } } my question is how can open the image from its path when I call from an android application? thanks in advance A: You can use third party libraries like Glide It's pretty straight forward. Check their sample for more info Do note you will require a valid url to successfully load an image into ImageView GlideApp.with(this) .load("http://someAwesomepic") .into(imageView); You can also use Picasso, which is another very awesome library to do the similar job Both the libraries are very flexible and can help you get your job done Adding to Joe C comment, you need to create a dedicated directory for Images which can be publicly accessible. Store all your images into this directory. Now in your database just store the image name with a path eg /images/IMG_123.jpg When building the response append the base url with the above path
{ "pile_set_name": "StackExchange" }
Q: Modular Exponentiation with power not within long long limit. I came across a problem where I need to find $x^y$ mod $p$ where $p$ is prime.It is an easy problem which can be find in $O(\log y)$ complexity but the twist in the problem is that value of $y$ is $n\text{C}r$ where $n$ can go up to 5000 hence $y$ can be very large and cannot be stored (can be of $10^{1500}$).So is there any way to find $x^y$ mod $p$? I have tried this (x^(y mod p)) mod p but that doesn't give the correct answer.Please help. A: The trick here is to calculate $x^{y\mod (p-1)}$ mod $p$. This works by Fermat's little theorem: $x^{p-1}\equiv 1$ mod $p$, and so if $y\equiv k\mod p-1$ then $y=m(p-1)+k$ for some $m$ and $x^y\equiv x^{m(p-1)}x^k\equiv 1^mx^k$ mod $p$.
{ "pile_set_name": "StackExchange" }
Q: animation in for zooming image in middle jquery I have to do an animation in which an image should move to particular point on click and in middle of this, I have to zoom the image and at last it will retain its size. Example: if div height = 100 and width = 100 then , in starting of animation it will be 100*100 in middle of animation it will be 120* 120 in last of animation it will be 100*100 here is what i have tried this is doing half of the part but not what i want <!DOCTYPE html> <head> <meta charset="utf-8"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="js/jquery.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"> </script> <style type="text/css"> .logo{width:116px; height:116px; position:relative;border:1px solid black; } </style> <script> $(document).ready(function(){ $(".logo").click(function(){ // $(".logo").css("-webkit-transition","width 2s ease, height 2s ease"); // $(".logo").css("-moz-transition","width 2s ease, height 2s ease"); // $(".logo").css("-o-transition","width 2s ease, height 2s ease"); // $(".logo").css("transition","width 2s ease, height 2s ease"); $(".logo").animate({height:'326px', width:'326px', left:'250px', top:'250px'},5000,"easeInOutSine",function() { $( this ).after( "<div>Animation complete.</div>" ); }); }); }); </script> </head> <body> <img src="img/coke.png" class="logo"/> </body> </html> A: Please test this script as you didn't provide a fiddle and i'm lazy to create one for you $(".logo").animate({ left:'250px', top:'250px'}, { queue: false, duration: 3000 },"easeInOutSine",function() { $( this ).after( "<div>move complete.</div>" ); }); $(".logo").animate({ height:'326px', width:'326px', { queue: false, duration: 1500 },"easeInOutSine",function() { $( this ).after( "<div>expand complete.</div>" ); }).animate({ height:'110px', width:'110px', { queue: false, duration: 1500 },"easeInOutSine",function() { $( this ).after( "<div>contract complete.</div>" ); }); take a look @ http://api.jquery.com/animate/ and check out queue: false
{ "pile_set_name": "StackExchange" }
Q: Convert wrong data type to null with T-SQL bulk insert I'm converting an Access mdb application to a WPF application that uses a local t-sql database. In this application it imported a tab-delimited text file using DoCmd.TransferText, so I am using a t-sql bulk insert instead as follows: CREATE PROCEDURE [dbo].[sp_insLoans] @FileLocation nvarchar(500) AS DECLARE @sql NVARCHAR(4000) = 'BULK INSERT tblLOAN FROM ''' + @FileLocation + ''' WITH ( FIELDTERMINATOR =''\t'', ROWTERMINATOR =''\r'' )'; exec(@sql) However for whatever reason, sometimes these files have a letter in a numeric column. The DoCmd.TransferText function appears to convert it to null/blank. Is there a way that I can convert this letter to null for that column when I do the bulk insert? A: I agree with G Mastros. I would put it into a temp table and then run a replace command to remove the characters. This will take you through removing any non numerical characters: https://www.sqlservercentral.com/Forums/Topic470379-338-1.aspx Cheers Will
{ "pile_set_name": "StackExchange" }
Q: Referencing c# assembuly due to vb.net conversion problems After converting code from c# to vb.net, pointers and unsafe code there's a problem, and due to the application i need to use them, so i've read about creating an assembuly and referencing it in a vb.net application. i've got so far but im not sure how to go about it now. Pointer (Of Byte) Problem Public Function Recognize(image As UnmanagedImage, rect As Rectangle, ByRef confidence As Single) As Byte(,) Dim glyphStartX As Integer = rect.Left Dim glyphStartY As Integer = rect.Top Dim glyphWidth As Integer = rect.Width Dim glyphHeight As Integer = rect.Height Dim cellWidth As Integer = glyphWidth \ glyphSize Dim cellHeight As Integer = glyphHeight \ glyphSize Dim cellOffsetX As Integer = CInt(cellWidth * 0.2) Dim cellOffsetY As Integer = CInt(cellHeight * 0.2) Dim cellScanX As Integer = CInt(cellWidth * 0.6) Dim cellScanY As Integer = CInt(cellHeight * 0.6) Dim cellScanArea As Integer = cellScanX * cellScanY Dim cellIntensity As Integer(,) = New Integer(glyphSize - 1, glyphSize - 1) {} Dim stride As Integer = image.Stride Dim srcBase As Pointer(Of Byte) = CType(image.ImageData.ToPointer(), Pointer(Of Byte)) + (glyphStartY + cellOffsetY) * stride + glyphStartX + cellOffsetX Dim srcLine As Pointer(Of Byte) Dim src As Pointer(Of Byte) For gi As Integer = 0 To glyphSize - 1 srcLine = srcBase + cellHeight * gi * stride For y As Integer = 0 To cellScanY - 1 For gj As Integer = 0 To glyphSize - 1 src = srcLine + cellWidth * gj Dim x As Integer = 0 While x < cellScanX cellIntensity(gi, gj) += src.Target x += 1 src += 1 End While Next srcLine += stride Next Next ' calculate value of each glyph's cell and set ' glyphs' confidence to minim value of cell's confidence Dim glyphValues As Byte(,) = New Byte(glyphSize - 1, glyphSize - 1) {} confidence = 1.0F For gi As Integer = 0 To glyphSize - 1 For gj As Integer = 0 To glyphSize - 1 Dim fullness As Single = CSng(cellIntensity(gi, gj) / 255) / cellScanArea Dim conf As Single = CSng(System.Math.Abs(fullness - 0.5)) + 0.5F glyphValues(gi, gj) = CByte(If((fullness > 0.5F), 1, 0)) If conf < confidence Then confidence = conf End If Next Next Return glyphValues End Function So i created a c# project and placed the code original c# part of the code within it namespace CTCAM: public interface interfaceCTCAM { int Recognize(UnmanagedImage image, Rectangle rect, out float confidence); } public class Class1 { public byte[,] Recognize(UnmanagedImage image, Rectangle rect, out float confidence) { int glyphSize = 5; int glyphStartX = rect.Left; int glyphStartY = rect.Top; int glyphWidth = rect.Width; int glyphHeight = rect.Height; int cellWidth = glyphWidth / glyphSize; int cellHeight = glyphHeight / glyphSize; int cellOffsetX = (int)(cellWidth * 0.2); int cellOffsetY = (int)(cellHeight * 0.2); int cellScanX = (int)(cellWidth * 0.6); int cellScanY = (int)(cellHeight * 0.6); int cellScanArea = cellScanX * cellScanY; int[,] cellIntensity = new int[glyphSize, glyphSize]; unsafe { int stride = image.Stride; byte* srcBase = (byte*)image.ImageData.ToPointer() + (glyphStartY + cellOffsetY) * stride + glyphStartX + cellOffsetX; byte* srcLine; byte* src; for (int gi = 0; gi < glyphSize; gi++) { srcLine = srcBase + cellHeight * gi * stride; for (int y = 0; y < cellScanY; y++) { for (int gj = 0; gj < glyphSize; gj++) { src = srcLine + cellWidth * gj; for (int x = 0; x < cellScanX; x++, src++) { cellIntensity[gi, gj] += *src; } } srcLine += stride; } } } // calculate value of each glyph's cell and set // glyphs' confidence to minim value of cell's confidence byte[,] glyphValues = new byte[glyphSize, glyphSize]; confidence = 1f; for (int gi = 0; gi < glyphSize; gi++) { for (int gj = 0; gj < glyphSize; gj++) { float fullness = (float) (cellIntensity[gi, gj] / 255) / cellScanArea; float conf = (float)System.Math.Abs(fullness - 0.5) + 0.5f; glyphValues[gi, gj] = (byte)((fullness > 0.5f) ? 1 : 0); if (conf < confidence) confidence = conf; } } return glyphValues; } } Once i done that i deleted the "recognized" function from the vb code and imported the libary created "Imports CTCAM.Class1". So in the VB application, Later in my code and error is showing, and this is where im not sure where to go now. Dim glyphValues As Byte(,) = Recognize(glyphImage, New Rectangle(0, 0, glyphImage.Width, glyphImage.Height), confidence) The word "Recognize" is highlighted with the following error information: "Reference to a non-shared member requires an object reference." Any help would be great. Many Thanks, Pete A: You need to make an instance of 'Class1' Dim class1instance As New Class1() Dim glyphValues As Byte(,) = class1instance.Recognize(glyphImage, New Rectangle(0, 0, glyphImage.Width, glyphImage.Height), confidence) Another option would be to make the function Shared.
{ "pile_set_name": "StackExchange" }
Q: Probability of getting a mirror image In a suitable font, the letters A, H, I, M, O, T, U, V, W, X, and Y are all mirror images of themselves. A string made from these letters will be a mirror image of itself if it reads the same backward and forward: for example, MOM, YUMMUY, MOTHTOM. If a four-letter string in these letters is chosen at random, what is the probability that this string is a mirror image of itself? A: $121 / 11^4$ seems right to me.
{ "pile_set_name": "StackExchange" }