INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Storing large amounts of data in the Asp.net session I'm writing a C#/asp.net page, and currently lots of data (say 100 000 Datetime int pairs) that i pull out of a database on page load, however loading the same data every page load seems a little silly. I've considered storing this value in the session, but multiple browser tabs seems to be causing an issue. Is there a better way to store these values, and is using the session appropriate if i need to support multiple browser tabs?
Your session eats up a lot of server memory. You could store your session in a database (which defeats the purpose since this is the reason why you want to store them in the session in the first place), but reading between the lines (why would each visitor need 100,000 unique datetime pairs?) I think you should really look into storing these values in the cache (if they're the same for all users). The problem with storing 100k int pairs in the session is that it might work for 1 or 2, hell even a dozen users maybe. But when your website gets popular its not scalable at all. Your server won't be able to store 500,000 user sessions of 100k int pairs each. **You'll run out of memory pretty quickly**
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 2, "tags": "c#, asp.net, session" }
Python execute While loop even if condition is not met? I am creating a car game. There are only "start", "stop", "quit" commands. Any other command is not recognized. command = "" while command != "quit": command = input("Command: ") if command == "start": print("Car ready to go") elif command == "stop": print("Car stopped") else: print("I don't understand that") else: print("Game exited") All commands work fine except "quit". With the while loop, it causes both the else statements to be executed and prints: I don't understand that Game exited The command = "quit" should render the while condition `False` and thus skip ahead to execute only the outer else statement. Why is it executing both else statements even thought the while condition is not met?
Python programs run line by line. A while loop does not guarantee its condition thoughout the whole indented block. So it's not equivalent to "as soon as [condition] is not met, jump out of the while block" Your `input()` is inside the while loop. So it will execute until the end of the while loop first, until it reaches the top of the while loop and checks the condition of the while loop again. A typical workaround is to have a while True: command = input("Command: ") if command == "quit": break ...
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "python, while loop" }
The term for a kitchen device I want to translate a Russian fairy tale. There is a "device" I need an equivalent for. In Russian it is called "ухват" (uhvat), and it is used to put pots on the coals/into the oven. Is there anything alike in English? (The Google's "grip" doesn't fit).
According to this, it translates to an "oven fork". I did an image search for "ухват" and then for "oven fork" and some of the same images appeared in both as you can see here and here, respectively. For the benefit of the people asking for a photo in the comments, here it is: ![enter image description here](
stackexchange-english
{ "answer_score": 1, "question_score": 1, "tags": "meaning, nouns, translation" }
Link not being processed At What kind of topological invariants can you get from just Hopf algebras?, link [4] is not being processed: ![What kind of topological invariants can you get from just Hopf algebras? with link not processed]( However, it is there in the source: [1]: [2]: [3]: [4]: Why isn't it processed?
Apparently you need to let the `<hr>` tag its own paragraph. I fixed it now.
stackexchange-meta_mathoverflow_net_7z
{ "answer_score": 3, "question_score": 2, "tags": "bug, hyperlinks" }
How many wires should be in a new thermostat cable? When roughing in thermostat wire, how many pair wire would you use to cover most thermostats? I'm asking because keep seeing questions about C wire and wifi.
For traditional Heat + Fan + AC systems, you need 4 for the system to work _at all_ , and 5 if you want to support the C wire for smart 'stats. However when you get into heat pump and multistage systems, just throw an 8 in there - it's readily available and not that much more expensive. You're not going to get very many latté's with the cost savings from using 4-wire.
stackexchange-diy
{ "answer_score": 5, "question_score": 6, "tags": "wiring, thermostat, thermostat c wire" }
Adding a hook to Remove item in a woocommerce cart In the woocommerce cart, when the user presses the REMOVE ITEM button on the cart I am trying to retrieve some post meta from an item in the cart. Something like: $removed_stock = get_post_meta( $product_id, 'more_info_data', 'x' ); To do that I am adding an action: function ss_cart_updated( $item_id ) { print "<pre>"; print_r (WC()->cart->get_cart()); print "</pre>"; exit; }; // add the action add_action( 'woocommerce_cart_item_removed', 'ss_cart_updated' ); Unfortunately this only list all the products in the cart that have been not removed. The item that has not been removed it is not listed anymore. I tried "woocommerce_get_remove_url" and "woocommerce_cart_item_remove_link" they dont seem to do anything for me. Thanks so much!
I think you need to use the `woocommerce_remove_cart_item` which runs just before the item is actual unset from the cart contents array. `woocommerce_cart_item_removed` happens _after_ the item is removed, so as you have found out there's no way to get any information about the product. Untested, but try this: function ss_cart_updated( $cart_item_key, $cart ) { print "<pre>"; $product_id = $cart->cart_contents[ $cart_item_key ]['product_id']; print_r(get_post_meta( $product_id, 'more_info_data', true )); print "</pre>"; exit; }; add_action( 'woocommerce_remove_cart_item', 'ss_cart_updated', 10, 2 );
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 4, "tags": "php, wordpress, woocommerce" }
Comparing SQL date without current month I have a table in Access with string columns and a date column. I want to get all the rows from the table when the date is lower than 22.10.2010, except this month. So, i need the rows from 30.09.2010 to ... I tied something, but I figured out it's not right: SELECT name FROM table WHERE YEAR(date)<=2010 AND MONTH(date)<10 But this solution it's not good, and i have no other idea. Could you help me with a general solution, pls? Thanks
The zeroth day of a month is the last day of the previous month: DateSerial(Year(Date()),Month(Date()),0) Therefore: SELECT [name] FROM [table] WHERE [date]<=DateSerial(Year(Date()),Month(Date()),0)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "sql, ms access, date math" }
Detect Element.Style changes with Javascript I am at the moment working on a little extension to enhance a website namely the google plus post box. I want to move it to the very left of the monitor. This post box however resets its values every time it is opened. Basically I would like to kill off that behavior, and thought I could just monitor the element for element.style changes, and overwrite them again. However DOMAttrModified seems not to work for stuff like that Additionally to that I have found that when the post box is closed it ceases to exist oO? Maybe someone here has an idea how to tackle this I could of course just loop an operation that sets the style every second or so. but no thanks XD thanks a lot for helping :)
Mutation events are deprecated, DOMAttrModified is not and will not be supported by webkit browsers. Use Mutation Observers instead. Alternatively, you can try this workaround.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 9, "tags": "javascript" }
Rails change background of new.html.erb page On the index.html.erb page, I am using a custom black background. This custom background, by default, is also used on all other pages including the page for new.html.erb (_form.html.erb), edit.html.erb, etc... Is there a way to change the background on the other pages (for example a background that is white) on the other pages such as new.html.erb? If so, how can one do this?
I think you're looking for layouts: < Specifically, you could have a `black_background` and a `white_background` layout. Then you just render your partials with one or the other layout depending on which you want.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "ruby on rails, ruby, ruby on rails 3.2" }
Magento 2 cancel order from myaccount page Cancelling order in magento 2 programatically: I implemented the module in magento 1 in which I will cancel the pending order from customer my account page. Please refer to the code below which I implemented in the magento 1: $order = Mage::getModel('sales/order')->load($orderId); $order_status=$order->setState(Mage_Sales_Model_Order::STATE_CANCELED, true)->save(); I want to implement the same functionality in magento 2. Does anyone know how to implement it? I loaded the order with order id in magento 2, but am unable to cancel the order.
You should use API (more about magento2 API concepts) for that, example how to use it in your class: <?php use Magento\Sales\Api\OrderManagementInterface; class A { /** * @var OrderManagementInterface */ private $orderManagement; /** * @param OrderManagementInterface $orderManagement */ public function __construct(OrderManagementInterface $orderManagement) { $this->orderManagement = $orderManagement; } public function cancelOrderOne() { $orderId = 1; $isCanceled = $this->orderManagement->cancel($orderId); } }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "magento, magento2, magento 2.0" }
Debugging Syntax error: "}" unexpected (expecting "fi") The service for a piece of software I just installed (from a provided `.deb` file) on a Ubuntu server won't start. When running the service I get the error: /etc/init.d/matrixsa: 44: Syntax error: "}" unexpected (expecting "fi") Here is the relevant part of the script. Not being versed in shell scripting I don't know if this is valid: if [ -f /etc/rc.d/init.d/functions ] then . /etc/rc.d/init.d/functions else function action { echo "$1" shift $@ } # <-- this is line 44 function success { echo -n "Success" } function failure { echo -n "Failed" } fi
`$@` could contain anything, even things which make your function suddenly syntactically invalid. Quote it instead. Here is a less breakable version of the script: if [ -f /etc/rc.d/init.d/functions ]; then . /etc/rc.d/init.d/functions else action() { printf '%s\n' "$1" shift "$@" } success() { printf Success ; } failure() { printf Failed ; } fi If you are using `bash` or similar, you could use the following as the `action` function: action() { printf '%s\n' "$1" "${@:2}" } If it is important that it splits on IFS like the original script (it probably isn't), unquote `$@`. It's also possible that you're running this in a non-bash shell. `function` is a bashism, use `func()` instead.
stackexchange-unix
{ "answer_score": 13, "question_score": 6, "tags": "shell script, services" }
Having Problems with $('img').load(function(){something}); in ie and firefox Here is my code. This centers images vertically with the class productImage. I have a bunch of images within the class. This works fine in chrome. but itermittently in ie and firefox. I can't figure out what's going on. I think it has something to do with when the image is getting loaded. I though by binding the load event to each image, it would always wait until each image is loaded until it fires, but it is not ... sometimes. Can anyone shed some light on this? $('img.productImage').each(function(){ var jproductImage = $(this); jproductImage.load(function(){ jproductImage.css({ 'margin-left' : -jproductImage.width()/2 + 'px', 'margin-top': -jproductImage.height()/2 + 'px' }); }); }); Thanks, Matt
It could be that the images are getting cached by the browser, thereby preventing the `.load` event from firing. You can circumvent this problem by testing for the `.complete` property on each image, and where it is set, manually triggering the `.load` event: $('img.productImage').one("load",function() { $(this).css({ 'margin-left': $(this).width() / 2 + 'px', 'margin-top': $(this).height() / 2 + 'px' }); }).each(function() { if(this.complete) $(this).trigger("load"); }); Also, your outer `.each` is a bit redundant. The above is all that is needed.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, jquery" }
Offline template rendering similar to MVC partial views? I want to refactor an existing MVC action so that it can be used offline to build email content. The action just fetches a model by Id and hands it over to the view, where the view renders it's fields. There is a foreach loop in the view. My first thought was to just create an html file and do string search and replace in it. Is there any template rendering libraries I should consider instead?
You may take a look at `RazorEngine`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, .net, asp.net mvc, template engine" }
RSpec having trouble stubbing method called with inline rescue I'm trying test a method on a controller: def a_method(list) @users = [] list.each do |x| if user=User.find(x) rescue nil @users << user end end end In my Rspec example I have : it "should do something" do User.stub :find => 'user' controller.a_method([1,2,3,4]) assigns[:users].should == ['user','user','user','user'] end Problem: it always rescues the find method `user=User.find(x) rescue nil`, even though I've stubbed it out. If I remove the `rescue nil` it works fine. Any ideas?
The if conditional doesn't accept a statement modifier such as `rescue` half way into the statement. You can put the rescue at the end of the complete `if` statement as in: if user=User.find(x) @users << user end rescue nil
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby on rails, rspec, stub" }
Playing .m3u8 audio stream file through monotouch I am currently developing an iPhone app that streams audio. The URL I wish to stream is an m3u8 file at the following link: < I can load the NSRequest on a webview which will open the stream but this pushes my application to the background when it opens the stream and the only way to get back to the app is to close the stream. I would prefer a play button on my view which will start playing the stream when it is clicked and the user should be able to switch tabs within the application without stopping the stream. In essence, the stream should continue playing until the user deliberately stops it. If somebody can give me any idea as to how to do this within MonoTouch and C# for an iPhone application or point me to a tutorial, that would be great. I have scoured Google but with no avail.
@Joachim. I have also build a streaming solution and accomplished this in a different way. With a bit of poking around I found the actual Shoutcast stream at < Not sure if this will help you in your situation. Perhaps you can generate your own playlist. Good luck!. Riaan
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, iphone, ios, xamarin.ios, audio streaming" }
Prove that $\sum_{k = 0}^{49}(-1)^k\binom{99}{2k} = -2^{49}$ I am preparing a class on the binomial of Newton. One of the exercises at the end of the chapter turns out to be very hard for me: > Prove that $$\sum_{k = 0}^{49}(-1)^k\binom{99}{2k} = -2^{49}$$ I tried to use a clever way of rewriting the binomial coefficients and also tried to use the binomial of Newton to rewrite $2^{49}$ as $\sum_{k = 0}^{49}\binom{49}{k}$, but with no result. I also tried to use a proof by induction, but got stuck also. Any hint would be appreciated.
**Hint** : It is the real part of $$(1+i)^{99}=\Bigl(\sqrt 2\,\mathrm{e}^{\tfrac{i\pi}4}\Bigr)^{99}.$$
stackexchange-math
{ "answer_score": 7, "question_score": 3, "tags": "binomial coefficients, binomial theorem" }
Unclear how to unhold an "on hold" question This question is related to this question about on hold. As it is, the "On Hold" explanation just says "edit your question or leave a comment". I thought it was odd that doing that would "unhold" the question, but I followed the instructions anyway... and, of course, nothing happened. I just spent 10 minutes reading DIY.stackexchange's FAQ pages on this topic to try and figure out how to get a question I asked out of "on hold". Still confused, I came here to ask for more clarity. I'm still not sure **how** to go about getting my question unheld, or if I need to do anything more.* There are **two** answers I am seeking: 1. How to unhold a question that has been placed on hold by a moderator? 2. Is there anything else I can/should do to get my question off hold (I'm considering just deleting and re-asking it at this point)?
Once a question that has been put on hold has been edited, it is placed in a reopen queue, for peers to review and (if deemed good enough), reopen. It may be that the edits have not improved the question to the degree that it will get reopened. * * * I mentioned to the Community Team that the help center documentation on this could probably use some love in regards to "next steps".
stackexchange-meta
{ "answer_score": 19, "question_score": 17, "tags": "discussion, support, on hold" }
I can't create a indepente org.apache.log4j.Logger I have a web Application Java class running into a Wildfly named Sincronizador. I did create a specific org.apache.log4j.Logger in Sincronizador.java but the `logger.log(...)` also put info in the Wildfly `server.log`. I would like to log info only in this logger Logger logger = Logger.getLogger(SASComm.class); logger.removeAllAppenders(); RollingFileAppender rollingFileAppender = new RollingFileAppender(); rollingFileAppender.setLayout(new PatternLayout("[%d{dd-MM-yyyy HH:mm:ss SSS}][%p] %m%n")); rollingFileAppender.setMaxBackupIndex(7); rollingFileAppender.setMaxFileSize("50MB"); rollingFileAppender.setName("Sinc"); rollingFileAppender.setFile(getLogFile()); rollingFileAppender.activateOptions(); logger.addAppender(rollingFileAppender);
You just need to set the `additivity` flag to `false` on your logger so that it doesn't inherit from a parent logger: logger.setAdditivity(false); This line `logger.removeAllAppenders();` will remove all the assigned appenders from this logger but the inheritance is still there (at least from the `rootLogger`) which you need to remove as well.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, log4j" }
Growth and shrinking rate of measurable sets along the boundary **Definitions:** Let $E$ be a measurable, bounded subset of $\mathbb R^n$ with nonzero Lebesgue measure. Denote by $\partial E$ the measure theoretic boundary of $E$, defined as the set of points in $\mathbb R^n$ where the measure theoretic density of $E$ is not $0$ or $1$. For $\varepsilon > 0$, write $\partial E_\varepsilon$ for the set of points within distance at most $\varepsilon$ of $\partial E$. Write $E^+_\varepsilon$ for the set $E \cup \partial E_\varepsilon$, and $E^-_\varepsilon$ for the set $E \setminus \partial E_\varepsilon$. **Question:** Is it true that for all bounded measurable sets $E$, we have $\limsup_{\varepsilon \to 0} \frac{\mu(E^+_\varepsilon)\mu(E^-_\varepsilon)}{\mu(E)^2} \leq 1$?
I think one of the classic counterexamples works here, to show that this is false: Let $\\{q_i\\}_{i\in\mathbb{N}}$ dense in $[0,1]^n$, $\delta >0$ and construct $$E = \bigcup_{i\in\mathbb{N}} B_{\delta 2^{-i}}(q_i).$$ Then $\mu(E) \leq c\delta^n$, but $E$ is dense in $[0,1]^n$. If I am not completely mistaken (You might need to choose the $q_i$ so that the balls don't intersect), then for the measure theoretic boundary it is still true that $\overline{\partial E} \cap [0,1]^n = [0,1]^n \setminus \operatorname{int}(E)$. So in particular $[0,1]^n \subset E_\epsilon^+$ for any $\epsilon > 0$ and thus $\mu(E_\epsilon^+) \geq 1$. Finally, $E_\epsilon^-$ includes most volume of all balls such that $\delta 2^{-i} \gg \epsilon$, so you can show that $\mu(E_\epsilon^-) \to \mu(E)$. But then $$\limsup_{\epsilon \to 0} \frac{\mu(E_\epsilon^+) \mu(E_\epsilon^-)}{\mu(E)^2} \geq \frac{1 \cdot \mu(E)}{\mu(E)^2} > \frac{1}{c\delta^n}$$ which is unbounded.
stackexchange-mathoverflow_net_7z
{ "answer_score": 3, "question_score": 2, "tags": "geometric measure theory" }
SWT: Get system image for "settings" (cog?) I would like to make it as native as possible. So I need a possibility to get system icons. The only thing I can find on this is how to get dialog icons like `SWT.ICON_ERROR` and so on. Is there a chance to get other system icons like open, save, copy, and so on?
This is currently not possible with SWT. There is a bug report here. * * * What you can do however, is use the Eclipse icons which can be found here. There is also a related question here. Hope this helps.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, swt" }
Log to ELK from Nomad without using container technology We are using Hashicorp Nomad to run microservices on Windows. We experienced that allocations come and go, but we would like to have centralized logging solution (ideally ELK) for all logs from all jobs and tasks from multiple environments. It is quite simple to do it with dockerized environments, but how can I do it if I run `raw_exec` tasks?
There's nothing specific to containers for log shipping other than the output driver. If containers write their logs to volumes, which Nomad can be configured to do, then the answer is the same. Assuming your `raw_exec` jobs write logs into the local filesystem, then you need a log shipper product such as Filebeat or Fluentd to watch those paths, then push that data to Elastic / Logstash.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "devops, nomad, hashicorp" }
Configure Pop Up Layout A noobish question. Can someone tell me where to configure this layout which pops up when hovering over ? !enter image description here I searched under "Users" and I can see a layout called "Compact Layout" but looks like that will be available only for Salesforce1.
**For Standard Objects:** Click on Setup | Customize | (Object you wish to edit) | Page Layout **For Custom Objects:** Click on Setup | Create | Objects | (Object you wish to edit) | Page Layout Near the top right of the page there will be a link labeled **Mini Page Layout** How do I change the fields used by Hover Details?
stackexchange-salesforce
{ "answer_score": 2, "question_score": 1, "tags": "page layout, mousehover" }
indexação vs geração de página com PHP Tenho alguns produtos e todas as informações deles estão armazenadas no banco de dados. Quando algum cliente seleciona algum produto, é enviado via `POST` o `ID` do produto e assim é gerada uma nova página com o produto. E isso indexa no Google? A URL é algo assim: > site.com/produtos/vestido-manga-curta Onde `vestido-manga-curta` na verdade era um `GET` na `URL` que foi reescrita para não ficar algo como: > site.com/produtos?produto=vestido%20manga%20curta. A página `produtos.php` ali ela cuida de receber a `ID` e gerar a nova página(com as informações do produto..) Estou receoso com isso, preciso clarear as ideias..
Uma URL amigável precisa não somente ser amigável para ser bem posicionada numa pesquisa, mas sim possuir a `keyword` (chave/palavra de busca). Então o modo como você recupera o conteúdo da página e o apresenta/manipula* é indiferente pro Google. Veja esse caso real abaixo: !Demonstração keyword Embora o Google não posicione ou tire posições de seu site com base na sua URL, uma URL bem descritiva atrai mais cliques, e o CTR (taxa de cliques) é um critério para a avaliação de um site, então: `url descritiva > mais pessoas vêem meu site > melhor meu site é posicionado`. Pra ajudar também veja essa imagem que mostra como uma url deve ser estruturada. !Cheat seed url SEO
stackexchange-pt_stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "php, google" }
Having issues while importing whole sccs file into a wrapped selector I was looking for an easy way to prefix a style sheet and sass works just great. I don't need any building tool, just vs code sass extension, and press watch. What I did was, renamed the css to scss and then imported it inside the main style nesting in the selector I want, like: #wrapper { @import 'style1'; @import 'style2'; } The issue comes when one of the files has @font-face, they also get prefixed and that is a problem. I checked the issue tracker and apparently this is the correct behavior. < Given that. I am looking for a way to import only the @font-face rules to the root instead of the #wrapper selector. Is this possible without having to change the content of 'style1' or 'style2' ?
I was able to get around this problem with node sass magic importer. But again you need node scripting and terminal, but can be mitigated with a bundler which kinda is not what I want but at least I can sort of prebuilt it and still use a watcher. But given the hasle to set this up for such a simple thing I would just go to the style sheet and copy the font-faces to the root of the main file anyways. If anyone knows a solution with sass only please reply.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "css, sass" }
Markdown no break (nobr)? I've got a phone number in my markdown that tends to break over the end of the line. In HTML I could wrap it in a `<nobr>` tag to have it keep together properly. What is the correct way to do this in markdown? !screenshot of my problem
You can use non-break hyphen character ( `&#x2011;` ) 1&#x2011;111&#x2011;111&#x2011;1111 for 1-111-111-1111 Or you could need the phone number format with spaces in between, then use no-break space character ( `&#160;` ) 1&#160;111&#160;111&#160;1111 for 1 111 111 1111
stackexchange-stackoverflow
{ "answer_score": 29, "question_score": 27, "tags": "html, markdown, line breaks" }
resources to learn developing games with ndk+opengl in C++? i want to learn developing games with NDK+OpenGL . is it possible to write an android game only in C++ . i was able to run the native-activity sample in NDK sample folder .(which is written in C) . i was able to set up C++ support in Android.mk and Application.mk ( stl,exceptions,...) with the help of online NDK documentation . native-activity sample do not have any Java code . Can i assume that it is possible to write a game without Java (only in c++) . What are the resources ? which links and tutorials do you recommend ? should i learn those `jni` stuff too ?
Yes! It is possible to write a game completely in C++ and OGLES. This material should address what you are looking for: * Android NDK Game Development Cookbook * Beginning Android C++ Game Development
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 5, "tags": "android, c++, opengl es, android ndk" }
duplicated shapes on circle path? Illustrator CS6 I am wanting to create lots of small circles evenly spread to form a circle and am wondering what the best way to go about it is? I am thinking the blend tool? Is there a way to get it to follow a circular path? Otherwise I am just duplicating and using smart guides to align and then copying and mirroring to the other side. Just wondering if there is a more automatic way. ![enter image description here](
A circle with a **dashed stroke** having rounded caps .... ![enter image description here]( * Stroke weight controls the size of the "dots" (i.e. an 8pt stoke means the "dots" will have an 8pt diameter) * Rounded caps makes them "dots" * 0 dash makes the dash not have a length, resulting in "dots" * Gap controls the space between "dots" (center to center - so gap minus stroke weight = space between dots. In this case 15 - 8 = 7pts) You can then cut the circle however you need. Or simply apply the dashed stroke to a path you already have. ![enter image description here]( If you then need each "dot" as an individual object... ... choose `Object > Expand Appearance`, and then `Object > Expand` from the menu. You may need to then `Object > Ungroup` and/or `Object > Compound Path > Release` as well. ![enter image description here](
stackexchange-graphicdesign
{ "answer_score": 0, "question_score": 2, "tags": "adobe illustrator, cs6, alignment" }
Read joystick from Flash Can I read a joystick as input to a Flash applet? What options do I have? Ideally I want something portable between MacOSX and Windows, but something Windows specific is acceptable. (Is Linux too much to hope for?) I'm also hoping for analog(ish) support; that is I might be told that the joystick is 62% up and 32% left, not just "Up" or "Up and Left". I'd prefer something that doesn't require anything beyond the basic Adobe Flash plugin, but I should have the ability to install additional software. Searching, all I'm finding are various packages that read the joystick interface and feed keystrokes into Flash. These seem crude, don't support analog input, potentially add lag (this is for a game, so responsiveness matters), and potentially fragile (I can probably control the hardware and operating system that it runs on, but would prefer flexibility in case of last minute surprises).
to put it in simple, and crushing words: **flash cannot access joystick input** you should consider options pointed out by Branden, or some software, that'll convert joystick input to keyboard/mouse input ... other than that, there is this little library on bytearray.org ... greetz back2dos
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "flash" }
Help with the application of the infinite geometric series rule. We have that $$p=\sum_{t=1}^\infty \frac{d}{(1+r)^t}$$ Where _d_ is a constant and _r_ is a percentage. I am trying to deduce the result $d/r$ by the rule of infinite geometric series that states when _a_ is constant and $|x|<1$, $$\sum_{t=0}^\infty \ ax^t=\frac{a}{1-x}$$ The closest I get by substitutions is to $-d/r$. I would be very grateful if someone could help me. Thank you.
One may write, by a change of index, using the geometric sum evaluation, $$ \begin{align} \sum_{t=1}^\infty \frac{d}{(1+r)^t}&= \frac{d}{(1+r)}\sum_{t=1}^\infty \frac{1}{(1+r)^{t-1}} \\\\\\\&= \frac{d}{(1+r)}\sum_{t=0}^\infty \frac{1}{(1+r)^{t}} \\\\\\\&=\frac{d}{(1+r)} \cdot\frac{1}{1-\frac{1}{(1+r)}} \\\\\\\&=\frac{d}{(1+r)-1} \\\\\\\&=\frac dr. \end{align} $$
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "calculus, sequences and series" }
How are Amazon EBS snapshot's sizes calculated? First, how can I retrieve the space consumed by my EBS snapshots? Second, according to the documentation, Amazon EBS snapshot only backs up the blocks of an EBS volume that have been modified since the last snapshot creation. Suppose I have a 10GB EBS volume. I created the 1st snapshot for it. Since there is no "last" snapshot, I assume the first snapshot's size is 10GB. OK. And then I modified 1GB of data and created a 2nd snapshot. The 2nd snapshot's size should be around 1GB, right? However what if I deleted the 1st snapshot at this point? Is the 2nd snapshot still 1GB? If yes, can I still restore the 10GB EBS volume from the 2nd snapshot? Or does the 2nd snapshot automagically become 10GB?
This may answer Q2 (from < > Even though the snapshots are saved incrementally, when you delete a snapshot, only the data not needed for any other snapshot is removed. So regardless of which prior snapshots have been deleted, all active snapshots will contain all the information needed to restore the volume In your example after deleting the first snapshot you would not pay anymore for the 1GB in the first overwritten by the second snapshot, and you won't be able to restore the state of the first snapshot. But it's still quite opaque about how much a set of snapshots costs in terms of S3 usage.
stackexchange-serverfault
{ "answer_score": 5, "question_score": 13, "tags": "amazon ec2, amazon ebs" }
highlight multiple keywords in search i'm using this code to highlight search keywords: function highlightWords($string, $word) { $string = str_replace($word, "<span class='highlight'>".$word."</span>", $string); /*** return the highlighted string ***/ return $string; } .... $cQuote = highlightWords(htmlspecialchars($row['cQuotes']), $search_result); however, this highlights only one keyword. if the user enters more than one keyword, it will narrow down the search but no word is highlighted. how can i highlight more than one word?
regular expressions is the way to go! function highlight($text, $words) { preg_match_all('~\w+~', $words, $m); if(!$m) return $text; $re = '~\\b(' . implode('|', $m[0]) . ')\\b~'; return preg_replace($re, '<b>$0</b>', $text); } $text = ' Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. '; $words = 'ipsum labore'; print highlight($text, $words); To match in a case-insensitive manner, add 'i' to the regular expression $re = '~\\b(' . implode('|', $m[0]) . ')\\b~i'; NB: for non-enlish letters like "ä" the results may vary depending on the locale.
stackexchange-stackoverflow
{ "answer_score": 28, "question_score": 8, "tags": "php, html, search, arrays, highlight" }
Installing LyX over a vanilla TeXLive As the title says, I would like to install LyX over a vanilla TeXLive. However, when I do yum install lyx the whole distro TeXLive is set to be installed, which I obviously don't want. On the other hand, I didn't find RPMs for LyX on its website. So how can I install LyX in this situation? I'm running TL2014 on Fedora 20.
The rpm of 2.1.2 version for x64 can be downloaded here. In the same page you can check the dependencies, in case there are some extra packages you may have to install. Once you have the rpm file, follow the instructions provided in the askfedora forum here. In terminal: rpm -Uvh --nodeps lyx-2.1.2-1.fc20.x86_64.rpm
stackexchange-tex
{ "answer_score": 1, "question_score": 1, "tags": "lyx, texlive, installing, linux" }
Does having inertial mass demand that the particle must have (Higgs and other) potential energy? My understanding is that a photon is pure kinetic energy and has no inertial mass of its own (or probably too low to be significant). But for a box with two photons whose momentums cancel, the photons will affect the inertial mass, because now the energy is stationary when seen from outside. Except for gluons and photons all elementary particles get their mass from Higgs potential energy. Is this the only reason why photons don't have inertial mass? That they are purely kinetic and don't interact with any field to gain potential energy? So the picture I have in my head is that "stationary energy is what has the property of inertial mass and energy that has no form of stationary energy involved has no inertial mass."
I think your understanding is more or less correct, although I'm not entirely sure about some of the terminology you use. Massive elementary particles get their masses from the Higgs mechanism. Only particles that interact with the Higgs (by gauge interactions in the case of gauge bosons or Yukawa in the case of fermions) obtain masses in this way. As the Higgs is electrically neutral and colorless, it doesn't interact with the photon or the gluon, and thus those particles don't acquire masses from the Higgs. I wouldn't, however, describe the gluon or photon as purely kinetic, as both interact with other particles, just not the Higgs.
stackexchange-physics
{ "answer_score": 2, "question_score": 1, "tags": "mass energy, higgs" }
How to remake timezone with the regular expression? In my project I find timezones by id. Here is an example: (GMT+07:00) Indian, Christmas How can I make it look like this: Indian\Christmas with regular expression?
A single `preg_replace()` call will do the job. My pattern and replacement will match the whole string and replace it with the first and second capture groups which will be joined together by `\`. Code: (PHP Demo) $input='(GMT+07:00) Indian, Christmas'; echo preg_replace('/\S+ ([^,]+), (.+)/','$1\\\$2','(GMT+07:00) Indian, Christmas'); // output: Indian\Christmas Here is the Pattern Demo * * * This can be done several ways. If you'd entertain a non-regex method, here is one that leverages the static length at the front of each string: echo str_replace(', ','\\',substr($input,12)); // same output
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "php, regex, timezone, preg replace" }
How to use variables in SQL statement in Python? I have the following Python code: cursor.execute("INSERT INTO table VALUES var1, var2, var3,") where `var1` is an integer, `var2` and `var3` are strings. How can I write the variable names without Python including them as part of the query text?
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3)) Note that the parameters are passed as a tuple, `(a, b, c)`. If you're passing a single parameter, the tuple needs to end with a comma, `(a,)`. The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (`%`), because 1. It does not do any escaping or quoting. 2. It is prone to uncontrolled string format attacks e.g. SQL injection.
stackexchange-stackoverflow
{ "answer_score": 149, "question_score": 125, "tags": "python, sql" }
Python PYPY Cffi with Numpy array I'm trying to learn to use cffi, but I'm fairly new to c, so its a bit tricky. I'm practicing with a simple function to compute the sum of an array of doubles. Strangely my sum function is not giving the correct output. Can anyone see why? Am I handling the array correctly? I don't understand why I have to cast numpy arrays as pointers. from cffi import FFI import numpy as np ffi = FFI() ffi.cdef(""" double sum(double[], int); """) C = ffi.verify(""" double sum(double numbers[],int num_elements){ int i, sum=0.0; for (i=0; i<num_elements; i++) { sum = sum + numbers[i]; } return(sum); } """) numbers = np.random.gamma(1,1,100) print 'numpy', sum(numbers) numbers_p = ffi.cast('double *',numbers.ctypes.data) sm = C.sum(numbers_p, len(numbers)) print 'cffi', sm output: numpy 119.436940423 cffi 80.0
Notice how the result is a nice flat integer. Your C code is wrong. You need to specify the correct type for sum. Suggested changes: C = ffi.verify(""" double sum(double numbers[],int num_elements){ int i; double sum=0.0; //Now it has the correct data type. for (i=0; i<num_elements; i++) { sum = sum + numbers[i]; } return(sum); } """) With that correction: >>> sm = C.sum(numbers_p, len(numbers)) >>> sm 98.53688973595715 >>> sum(numbers) 98.536889735957146 >>> sum(numbers) == sm True
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, arrays, numpy, pypy, python cffi" }
「守りが甘い[上手]{うわて}」…どういう意味ですか? > ![]( > "If you play this stronger player for whom 'protection is sweet' you will be done for." is my best attempt to understand. The context in which this happens is the teacher of this go club sits down next to this group of first years to play the strongest arrival to his go club, a first year who is in fact at a professional level and should not be there. This teacher is making an offhand comment to Uno and the other first years sitting nearby. If necessary here is the panel just before this. So far I am getting the sense that can mean is relaxed and so on from the entries at eow.alc.co.jp, so perhaps "player for whom defense is easy?" but I am not sure.
I think this is 2 sentences really: and . here means not good enough/insufficient, in other words her defense is not enough. The second sentence then states that if she were to play a strong opponent, she would be done for.
stackexchange-japanese
{ "answer_score": 2, "question_score": 3, "tags": "idioms" }
How much does broadcast receiver cost for memory? _Scope:_ Have to update activity UI in different ways. Update depends on broadcasts received from service. _Problem:_ There are two common ways to find out which way UI should be updated: 1. register only 1 broadcast receiver but put different extras in its intent and check for them in OnReceive() method in activity; 2. register broadcasts for each update command. The 2nd ways seems to be more elegant and more understandable. But I wonder if it will consume more memory. What would you recommend? Thanks!
I agree with CommonsWare. From a perfomance standpoing this isn't really something you need to worry about. That said, I'd probably go with 2nd way for the sole reason that it will make your code more modular thus improving maintainability.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 8, "tags": "android, memory, broadcastreceiver" }
Migrating reports from SSRS 2005 to SSRS 2014 and SSAS 2005 cube to SSAS 2014? As SQL Server 2005 end of life is getting closer I'm facing inevitable job of migrating databases, SSIS packages, SSRS reports and SSAS cubes. Since newest version of SQL Server is SQL Server 2014 we are probably need to switch to it. I have read few texts on migrating from SQL Server 2008 to SQL Server 2014 but i have not found anything about migrating from SQL Server 2005. Have somebody else done something similar and can it be done in first place?
There is no definitive answer to your question, since it will totally depend on the complexity of SSIS packages, SSRS reports and SSAS Cubes. Doing in-place upgrade is always risky, since if something goes wrong, it would be difficult to rollback. A side-by-side migration is always a good and reliable method, since if something goes wrong, you already have a system up and running that you can point to. Always, test, test and test your migration and have a fully tested rollback plan. Use **upgrade advisor**.aspx) _(this touches DB Engine, SSIS, SSRS and SSAS)_ and fully address all the issues raised by it. * I have written a thorough answer for database migration and post restore steps * For SSRS migration, I have written it here. * Devin Knight talks about Upgrading Packages to SSIS 2012 and msdn has a whitepaper on 5 Tips for a Smooth SSIS Upgrade to SQL Server 2012 * For SSAS, this method should work in your case as well.
stackexchange-dba
{ "answer_score": 0, "question_score": 2, "tags": "sql server, ssrs, ssas" }
Issue in Exporting SSRS Reports to CSV I have an SSRS Report in which few columns will be made visible programmatically. The Report gets generated succesfully, but when it's exported to CSV, the columns whose "visible" attribute has been handled programmatically doesn't get exproted to CSV. 1. Is there a work-around for this issue? 2. What is the best way to implement hide logic for columns in SSRS so that there are no issues while exproting to CSV/Excel?
See < which explains that CSV (and XML) is a data format rather than a layout format. If the visibility is toggled via a formula as you're doing, it won't be rendered at all in CSV (even if the visibility setting makes it visible).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "ssrs 2008, reporting services" }
Using memcached to host images Im writing simple blogging platform in Flask microframework, and I'd like to allow users to change image on the front page but without actually writing it into filesystem. Is it possible to point src attribute in img tag to an object stored in memory?
Yes, you can do it. 1. Create a controller or serlvet called for example www.yoursite.com/getImage/ID 2. When you execute this URL, your program shoud connect to the memcached and return the image object that you have previously stored in it. 3. Finally when in your html you add: src="www.yoursite.com/getImage/ID" the browser will execute this url, but instead of reading a file from disk it will ask the memcached for the specific ID. Be sure to add the correct content-type in your response from the server in order that the browser understand that you are sending an image content. Fer
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, image, flask, memcached" }
Replacing text in button - radio Dialog creating a radio button dialog. I have found this tutorial which works great, however when the value is selected instead of a toast I want this to replace the text in the button. Any help would be greatly appreciated. @Override public void onClick( DialogInterface dialog, int which) { Toast.makeText( mContext, "Select "+choiceList[which], Toast.LENGTH_SHORT ) .show(); } }); AlertDialog alert = builder.create(); alert.show()
You mean like this: final String [] fruits = getResources().getStringArray(R.array.fruits_array); builder.setItems(R.array.fruits_array, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { pickFruitButton.setText(fruits[which]); dialog.dismiss(); } })
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "android" }
Pantheon Files context menu (contract) to run script in terminal I would like to be able to have an option in the default file manager to run an executable file in terminal like I have in KDE/Dolphin. This is useful in order to see the output (that could be temperature, countdown, etc...) I know how to create contract files, but what I need is the line starting with `Exec=`, namely I need to know what terminal to use and with what arguments.
gedit ~/.local/share/contractor/run_in_terminal.contract with [Contractor Entry] Name=Run in terminal Icon=terminal MimeType=application/x-sh;application/x-executable; Exec=pantheon-terminal -e %f Not any file can be run like this, the selected file has to be a proper executable script.
stackexchange-elementaryos
{ "answer_score": 1, "question_score": 0, "tags": "release loki, pantheon files, contract" }
Reducing integral in factor graph I have one question about reducing integral in factor graph. Applying message passing algorithm, I have create a final integral $g(z) = \int_x \int_y f(x, y , z) f_1(x) f_2(y) dx dy$ with the condition that $f(x, y, z) = 1$ when x + y = z and 0 otherwise. Moreover, $x,y \in R$ I wonder whether the above integral is equal to $g(z) = \int_x f_1(x) f_2(z - x) dx$ One of my friend say that the $\int_x \int_y ...$ is equal to $0$ but I dont think so. Would you please help me to solve this problem. Thank you.
The $y$ integral is indeed zero, because the range in $y$ is from $z-x$ to $z-x$. Your integral is trying to measure an area and the second is a one-dimensional line. Maybe instead you want $f(x,y,z)=\delta(z-x-y)$, the Dirac "delta function". It allows the transformation to the last, because it is "infinitely high" when $x+y=z$ to get you the extra dimension you need.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "integration" }
Is there a word which describes being unable to see the stars because of the brightness of the moon? I'm looking for something like "eclipsed" or "occulted", but caused by the brightness of the light rather than by anything solid being in the way.
You can say that the stars are _washed out_ by the moonlight: > ### intransitive verb > > 1. to become depleted of color or vitality: fade > Unlike _obscured_ , which to me has a connotation of either covering, physical obstruction, or darkness, _washed out_ paints a more appropriate picture, which is that there is **too much light**.
stackexchange-english
{ "answer_score": 16, "question_score": 11, "tags": "single word requests" }
HP printer and scanner installation First I downloaded printer driver software from HP. In the terminal window I always get error code 100 when installing an HP printer and scanner, so the installation does not work. How do I solve this?
Download from this link: < Next add execute parameter chmod +x hplip-3.18.9.run then execute as normal user. This installer can download and install dependencie. ./hplip-3.18.9.run After installation launch `hp-setup`
stackexchange-askubuntu
{ "answer_score": -2, "question_score": 1, "tags": "software installation, printing, hp, scanner" }
Setting URI to root directory in application for image source How do you set the URI for an image source to the root directory (i.e. same folder as your exe) in a WPF application? var myImage = new Image(); myImage.Source = new BitmapImage(new Uri("pack://application:,,,/AssemblyName;component/speedline.png", UriKind.Absolute)); I've tried the above and keep getting the following error message: _An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll. Additional information: Could not load file or assembly 'AssemblyName, Culture=neutral' or one of its dependencies. The system cannot find the file specified._ I am obviously doing something very wrong, but can guarantee that the png file can be found at `C:\Users\Admin\Documents\Visual Studio 2013\Projects\Speedy\Speedy\bin\Debug`, in the same folder as my exe file, but how do I reference it?
Create a new folder under the solution explorer called component and add the existing image under that. Now try using the Relative path. myImage = new BitmapImage(new Uri("/component/speedline.png", UriKind.Relative));
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "c#, wpf" }
If $X\subset \mathbb{R}$ is bounded and a infinity set, then $X \cap X^\prime \not = \emptyset$. First of all, let us define $X^\prime = \\{a \in \mathbb{R} \mid \forall\epsilon>0, ((a - \epsilon, a + \epsilon)-\\{a\\}) \cap X \not = \emptyset\\}$. The result is true when $X$ is an uncountable set: if $X \cap X^\prime = \emptyset$, then for all $x \in X$ there is an $\epsilon_x>0$ such that $((x - \epsilon_x, x + \epsilon_x)-\\{x\\}) \cap X = \emptyset$. It implies that all points of $X$ are isolated points. Then, $X$ should be a countable set (a contradition). So, $X \cap X^\prime \not = \emptyset$. But, what happens when $X$ is a countable set?
Consider $X = \left\\{\frac{1}{n} : n \in \Bbb N\right\\}.$ Then, $X' = \\{0\\}$ and $X \cap X' = \varnothing$.
stackexchange-math
{ "answer_score": 1, "question_score": 3, "tags": "general topology, analysis, metric spaces" }
Blender shrinkwrap modifier I have a question about shrinkwrap. I'm started mastering car course by cg masters I'm doing fine but and I can't understand one thing. As English is not my main language and I'm bad with it I need some explanation please, I don't understand the author correctly. 1) We have GUIDE mesh and BASE mesh. Which one is main and which one is the second ? 2) We make main mesh and then copy it to apply shrinkwrap on it mesh later. 2) Guide mesh is main and must have subdivision level 2 and base mesh subdivision level 4 ? Or vice versa ? I'm stuck. As I understand the process: we make simple mesh (guide) in subdivision 2, copy it, then we make detailed mesh (base) from copy in subdivision 4, apply shrinkwrap modifier with guide mesh.
CG Masters explained their modelling techniques much more thoroughly in their _Hard Surface Modelling_ course series. I'll try to explain it here. They are using the _Shrinkwrap Modifier_ to avoid shading issues. When you are using many modifiers such as _Boolean_ and _Subdivide Surface_ modifiers, it is common to encounter strange/unwanted shading (such as creases and sharp edges) on the surfaces. Thus, to avoid those shading issues, they create two meshes, a **base/guide** mesh and a **detailed copy** mesh. The base mesh has a minimal amount of detail on it, its purpose is to provide the proper shape and shading to the detailed mesh. The copy mesh has all of the details, such as boolean cutouts, on it. Since this results in shading issues, they use the _Shrinkwrap Modifier_ to stick the _Copy mesh_ onto the _Base Mesh_. Doing so transfers all of the normals from the _base_ to the _copy_ , fixing the shading while keeping the detail.
stackexchange-blender
{ "answer_score": 1, "question_score": 1, "tags": "shrinkwrap" }
$\Delta f=0$ in $\{x\in U:f(x)>0\}$ $\Rightarrow$ $\Delta f=0$ in $U$? Let $f\geq0$ be a continuous function satisfying $\Delta f=0$ in $\\{x\in U:f(x)>0\\}$. I was wondering if one could follow $\Delta f=0$ in $U$, especially in the cases $f\in C^2$ or $\Delta f=0$ in a weak sense. So I've tried to show it for $\Delta u=0$ in weak sense, e.g. $$ \int_U\nabla f\nabla\phi=0 $$for all $\phi\in C_0^\infty(U)$. I've considered instead of just $\phi$ the function $\phi \eta_\delta(f)$ with a bounded function $\eta_\delta$ satisfying $\eta_\delta(x)=0$ if $x\leq \delta$ and $\eta_\delta(x)=1$ if $x\geq 2\delta$. Then we get for the left side $$ \int \eta_\delta(f)\nabla f\nabla\phi+\int\eta_\delta'(f)\nabla f\nabla f $$Now I've tried to focus on some other conditions for $\eta_\delta'$ but it didn't get me any further. Any hints how you can show $\Delta f=0$ in $U$?
No. Let $U=\Bbb R^2$, $f(x,y)=|x|$.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "real analysis, analysis, partial differential equations, harmonic functions, laplacian" }
Cycles won't render from Render Region I press Ctrl+B and create a region for Cycles to render in Blender 2.92. The border is visible in the viewport and it all looks set to go. But every time I hit F12 to start the render, Cycles ignores the region and starts rendering as it would from the full camera view. I tried everything I could think of, including disabling the camera, but nothing seems to fix it. What could I be doing wrong? Could someone help me please? This is how I've set Cycles up for this scene. ![enter image description here]( And this is how I've set up the Output Properties. As you can see Render Region is ticked. ![enter image description here](
From Blender Manual: < Render Border is rendering part of your scene when you're in rendered shading mode. If you want a rendered result you'll have to set up a camera for that view.
stackexchange-blender
{ "answer_score": 0, "question_score": 0, "tags": "rendering, cycles render engine, render border" }
Chess problem - don't understand the solution Black to move: [fen "4rbk1/pp3pp1/1nq4p/8/1PP5/P3N1P1/Q2BrP1P/3R1RK1 b - - 0 1"] I've tried to solve this chess problem - black to move, find the best move. I couldn't work it out so I checked the solution, which was R8xe3. I don't understand why this is the best move - could someone explain please?
`1...R8xe3` wins a piece (the knight on e3), because either recapture leads to worse things for White, since the d2 bishop is pinned to the white queen, and the f-pawn recapture opens the possibility of mate on g2: [fen "4rbk1/pp3pp1/1nq4p/8/1PP5/P3N1P1/Q2BrP1P/3R1RK1 b - - 0 1"] 1...R8xe3 2.Bxe3 (2.fxe3 Qg2#) Rxa2
stackexchange-chess
{ "answer_score": 25, "question_score": 11, "tags": "learning, tactics, problems" }
Stacking fluid height divs I might be having a serious brain fart here but I can't seem to accomplish what I want to accomplish using divs and css. What I am trying to do is create a wrapper that fills the initial viewport view 100% then put more content underneath. If I was doing it in tables it would look roughly like this: <table height="100%"> <tr height="10%"> <td>Blank</td> </tr> <tr height="15%"> <td>Section 1</td> </tr> <tr height="25%"> <td>Section 2</td> </tr> <tr height="50%"> <td>Section 3</td> </tr> </table> Look here is more content under where the viewport is I have fiddled around using divs trying to accomplish this and I really want to avoid using a table for a layout (no thanks 2001) but has anyone accomplished this using just css and divs (no javascript)?
You probably forgot to set the height of the body to 100%? <div id="div1"></div> <div id="div2"></div> <div id="div3"></div> <div id="div4"></div> CSS: html,body { height:100%; } #div1 { height:10%; background:red; } #div2 { height:15%; background:green; } #div3 { height:25%; background:red; } #div4 { height:50%; background:green; } Works fine. You could of course achieve the same results with absolute or fixed positioning, but this is the clean and simple equivalent of your sample.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "css, html" }
Activate the crystal from far When I'm setting defenses at the other side of the map, is there a way to activate the crystal from far away, letting me kill enemies at the gate without running back-and-forth?
The default shortcut key for this is `G`. Unfortunately, last time I knew, there wasn't a way to do this if you're playing with a controller on PC.
stackexchange-gaming
{ "answer_score": 6, "question_score": 5, "tags": "pc, dungeon defenders" }
BluemixのNode.jsサンプルアプリが正しく動かない Bluemix Bluemix < FORKBluemixNode.jsWeb
Twitter API Twitter API Twitter APIURLTwitter Developer Center < APIURLTwitter→Manage Your Apps→Create New App→ 4 -API key -API secret -Access token -API secret 4app.js22 var tweeter = new twitter({ consumer_key: 'BFqTaQ24kn1mpdy7BmJZZkAgM', consumer_secret: 'XhHbGzHzVj0UG5WRApSryl32Ysqo8Ig1BHwdMgIOSjRny4DV0S', access_token_key: '2495803602-gx2KrW2YE0OYrBh1pLhpAzggDsae8wdEm3tWlwU', access_token_secret: 'qWaS4UoSOcdX1C1AvgYCJ8KWbCypBXyi1xqkD8ktLa3xA' }); Bluemix
stackexchange-ja_stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, node.js, bluemix" }
Wallis' axiom for parallel lines I want to prove, using the typical tools from a Hilbert plane, that the Wallis' axiom implies ($P_{\leq 1}$), where Wallis' axiom: Given a triangle $\Delta ABC$ and given a line segment $DE$, there exists a similar triangle $\Delta A'B'C'$, having side $A'B' \geq DE$. $P_{\leq 1}$: For each line $l$ and for each point $P\notin l$, there is at most one line containing $P$ that is parallel to $l$ I have already proved Proclo's axiom is equivalent to $P_{\leq 1}$, but I got no idea how to solve this problem... Any help would be appreciate.
There's a proof on page 153 of Greenberg, which you may be able to access here. If you can't access it or wish to fill in the details yourself, here's a proof sketch. Begin in the standard way: given _l_ and P, we construct the parallel line _m_ incident to P, and let Q be the foot of the perpendicular from P to _l_. Let _n_ be any other line through P. Now, we can pick a point R on _n_ , and drop the parallel to PQ, letting S be the foot. Apply Wallis's postulate to the triangle PSR and the line segment PQ. This produces a point T which must lie on _n_ and _l_.
stackexchange-math
{ "answer_score": 2, "question_score": 4, "tags": "geometry" }
Search for Header name exactly I have created a macro to search for Header name and insert a column, but the macro searches for the words containing what has been given in the command instead of searching the exact Header Name. 'Looks in entire first row. Dim rngHeaders As Range Set rngHeaders = Range("1:1") 'To set this to a specific sheetname, use Set ws = Sheets("Sheetname") Set ws = ActiveSheetSet Set rngUsernameHeader = rngHeaders.Find(What:="Account Name",After:=Cells(1,1)) If rngUsernameHeader Is Nothing Then Else rngUsernameHeader.Offset(0, 1).EntireColumn.Insert endif
You are missing a parameter for Find: Dim rngHeaders As Range Set rngHeaders = Range("1:1") Set ws = ActiveSheetSet Set rngUsernameHeader = rngHeaders.Find(What:="Account Name",After:=Cells(1,1), LookAt:=xlWhole) If Not rngUsernameHeader Is Nothing Then rngUsernameHeader.Offset(0, 1).EntireColumn.Insert
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "excel, vba" }
How to tell a participle from an adjective? What's the right way to tell a present passive participle from an adjective? I guess if the agent is mentioned (like in "Изменяемый **мною** проект"), then it's for sure a participle. But what about such cases, in which the agent is not mentioned? Like the ones below: > СМИ уже больше не обращают никакого внимания на постоянно **изменяемые** проекты городского правительства. > > Всё это **изменяемые** величины, а не константы. > > В отличие от "пианино" и "пальто" такие слова как "машина", "ковёр" и "контракт" - всё это **изменяемые** по падежам слова.
As far as I know, the participles mean "the ones which _are being changed_ " (your example #1), and the adjectives mean "the ones that _can be changed_ " (your examples #2 and #3). Anyhow, it is very difficult even for the native speakers of Russian to distinguish between the participles and the adjectives.
stackexchange-russian
{ "answer_score": 2, "question_score": 4, "tags": "грамматика, прилагательные, participle" }
How to cast from class type to interface I have an interface which is implemented by few classes. Based on the full name of the class I want to initialize the class objects. Interface, public interface InterfaceSample{ } Class files, public class ABC implements InterfaceSample{ } public class XYZ implements InterfaceSample{ } A sample test class, public class SampleManager{ public static InterfaceSample getInstance(String className) { InterfaceSample instance = null; try { instance = (InterfaceSample) Class.forName(className); } catch (ClassNotFoundException e) { e.printStackTrace(); } return instance; } } I am getting the following error, ** "Cannot cast from Class<capture#1-of ?> to InterfaceSample" ** How can I initialize the classes based on its name.
You're almost there: instance = (InterfaceSample) Class.forName(className).newInstance(); remember to mark the method with: throws Exception because `newInstance()` is marked so as well (it throws `InstantiationException` and `IllegalAccessException` to be precise).
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 0, "tags": "java" }
Need to find/highlight non occurences between 2 columns So I have 2 columns: Column A: 711 rows 10.35.6.0/24 10.132.42.0/24 10.35.7.0/24 10.142.224.0/24 10.142.208.0/24 10.35.8.0/24 10.134.224.0/24 10.134.20.0/24 10.134.240.0/24 Column C: 2337 rows 10.35.6.0/24 10.132.42.0/24 10.143.26.0/24 10.143.30.0/24 10.143.31.0/24 10.143.32.0/24 10.35.7.0/24 10.143.35.0/24 10.143.44.0/24 What I need is a column B that has the values of column C that do NOT occur in column A. In this example, column B should contain the values: 10.143.26.0/24 10.143.30.0/24 10.143.31.0/24 10.143.32.0/24 10.143.35.0/24 10.143.44.0/24 So it should have (2337 -711 = 1626) rows. Is there a way to do this in MS Excel?
Please try: =IFERROR(IF(MATCH(C1,A:A,0)>0,"",),C1) copied down to suit. The `copied down to suit` part may technically not be a loop but is very similar in nature (in so far as a ‘process’ is repeatedly applied to different data up to a given end condition – ie when ‘suit’ ends). =IF is a condition substantially the same as the If,…Then construct. =MATCH has an untold amount of code underlying it – even if proprietary (thankfully provided by M$ rather than laboriously put together by a user). VBA does not become "not programming" just because it uses functions. Cells are referenced RC, as is an option in VBA. The syntax can be critical, as in other programming. The formula takes inputs and (hopefully!) produces outputs – just as in other programming.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "excel, multiple columns" }
Multiple File Conversion with VLC media Player I have to convert a number of video files to audio format but its very painful and time consuming to convert them one by one. Is there a way to convert them in a batch with VLC player?
If you want to use `ffmpeg`, you can use the following to extract the audio parts of all WMV files in the current folder to uncompressed WAV (PCM audio): for f in *.wmv; do ffmpeg -i "$f" "${f%.wmv}.wav"; done Or MP3 – see the MP3 encoding guide for more info: for f in *.wmv; do ffmpeg -i "$f" -c:a libmp3lame -q:a 2 "${f%.wmv}.mp3"; done These are loops for Linux shells like Bash. For Windows, you'd do something like the following: for %%A IN (*.wmv) DO ffmpeg -i "%%A" "%%A.wav"
stackexchange-superuser
{ "answer_score": 6, "question_score": 4, "tags": "conversion, vlc media player, video conversion" }
Adding a variable to the end of a filename in perl I am using open to wrtie to a file. But i have a declared variable which i want added to the filename. I have tried everything possible but it isn't working. I have a script with about 100 lines but I am pretty sure my variable isn't changing anywhere in the code. my $env = "TEST"; some code; open $file, '>>', 'filename_$env.txt' or die; my code; But everytime it's returning the $env but not the value appended to the filename. I tried it without the _, with the "" around the $env,`` around the $env, curlies etc.. What silly mistake am i doing?
Use double quotes: open $file, '>>', "filename_$env.txt" or die; Single quotes would prevent variable expansion. Also, saying: open $file, '>>', "filename_${env}.txt" or die; would prevent any ambiguity if you have similar variable names.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "perl" }
Error 'No agent could be found with the following capabilities: msbuild, visualstudio, vstest' I'm setting up a new build server using TFS 2015 and after I configured the agent, when I tried to queue a build I got this error: > No agent could be found with the following capabilities: msbuild, visualstudio, vstest How can this be resolved?
Install Visual Studio on your build agent, then restart the build agent. Restarting the build agent will capture the added Capabilities.
stackexchange-stackoverflow
{ "answer_score": 59, "question_score": 74, "tags": "tfs, tfs 2015, azure pipelines" }
Beersmith Safale T-58 attenuation I've just measured the final gravity of a Belgian beer I've been brewing and it came out 4 points below the expected according to Beersmith: 1.022 rather than 1.018. It was 14 days in the fermenter. I should say that I haven't controlled the gravity throughout the fermentation so I'm not sure it finished. Now, my issue is that Beersmith's database marks the T-58 with a 71-75 range but Fermentis sheet says 70%. According to my measurements (OG 1.078, FG 1.022) Beersmith's says that the calculated attenuation was 70%, which is spot on with the value in the Safale's sheet. Could Beersmith's values be wrong or could I be missing something here? I'm a novice so apologies if I don't make much sense.
There's many factors that effect attenuation. The %s are a ball park under normal conditions, factoring average unfermentables and ABVs. _In theory all yeasts are capable of 100% attenuation of the fermentable sugars up to their ABV tolerance with a lot of nurturing._ In your case 4 points off may not be that far out of scope. If the sweetness is balanced it may be fine as it is. If not you can try a warmer secondary fermentation to finish out the few points.
stackexchange-homebrew
{ "answer_score": 4, "question_score": 3, "tags": "yeast, attenuation, beersmith" }
Spaces in URL cause linkage failure I can't get my URL to display properly. See the second link after the jump. How can I fix this?
I resorted to using an <a> tag, but it looks like the second space being escaped to %20 would've worked. (I caught one space, missed one, the first edit, which I then cleaned up within 5 minutes.) I also changed the parens in the URL to %28 and %29, but, IIRC, that isn't required in the "outline" format you had originally. Parens within the link text have always worked, AFAIK. ### Test inline outline inline [outline][1] [1]:
stackexchange-meta
{ "answer_score": 1, "question_score": 1, "tags": "support, markdown" }
Lucene problem with AND/OR Is there anyway I can guarantee that every document with all query terms always scores higher than documents with lesser query terms? Note that I don't want to stick with AND semantics. I still want to show results if there isn't any document that match all query terms.
one (safe, fast) thing you can try is to subclass DefaultSimilarity and adjust the computation of the coordination factor. The default computation is a basic fraction (so e.g. a document that only matches 2 out of 3 terms still gets 2/3 of the coordination factor as one that matches all 3). If this factor (matching all of the query terms) is important to you, then I suggest you explicitly boost documents that match all of the query terms even more, below is an example that cuts the score in half again for any document that doesn't match all the query terms. For example: @Override public float coord(int overlap, int maxOverlap) { return (overlap == maxOverlap) ? 1f : 0.5f * super.coord(overlap, maxOverlap); } ` This factor is described in more detail here: Lucene Similarity javadocs
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "java, lucene" }
Passing link parameters via sed I'm trying to insert an image link into a file for a wiki on a remote server. ssh [email protected] "sed -i -e '1i'[^ /var/www/wiki/page Works but I need to add the resize parameter after the file name but it doesn't work, how do I account for the spaces? ssh [email protected] "sed -i -e '1i'[^ height480 width=640^]'\'" /var/www/wiki/page sed: can't read height480: No such file or directory sed: can't read width=640^]\: No such file or directory
I'm not sure why you're quoting only the '1i'. You should quote the entire sed expression, if you have spaces in it. Try this: ssh [email protected] "sed -i -e '1i[^ height480 width=640^]'" /var/www/wiki/page
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "bash, sed" }
Creating a function of DT table in shiny I am trying to create a function for DT table where just specifying the columns name in the parameter, the column should get hidden dt_table <- function(data, colhidden = c(a)){ datatable(data, options = list( columnDefs = list( list(visible=FALSE, targets=colhidden) ) )) } dt_table(iris,colhidden = c('Species')) But unfortunately, the column is not getting hidden. Can anyone help me?
`targets` needs the column number which you can get with `match`. Try - library(DT) dt_table <- function(data, colhidden) { datatable(data, options = list( columnDefs = list( list(visible=FALSE, targets=match(colhidden, colnames(data)))) ) ) } dt_table(iris,colhidden = c('Species')) dt_table(iris,colhidden = c('Species', 'Sepal.Length'))
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "r" }
How did the cap economy make it to the east coast? My understanding of the cap economy is that it was established and maintained by the Hub in Fallout 1. Given that, canonically, how did that particular barter system become the de facto system on the east coast, specifically in the Capital Wasteland and surrounding environs (The Pitt, Point Lookout, etc.)?
Presumably the same way the Brotherhood of Steel made it out East. People moved, and brought the use of Caps as currency with them. Keep in mind, _Fallout 3_ occurs some 200 years after the bombs fell, and roughly a century after the events of the original _Fallout_. According to the Fallout Wiki, no explanation is offered as to why Caps are used in FO3, but presumably, given that the NCR has switched to it's own currency in FO2, this reflects how backward the DC wasteland is relative to the somewhat more rebuilt territories out west.
stackexchange-gaming
{ "answer_score": 8, "question_score": 11, "tags": "fallout 3, fallout" }
considering NullPointerException as a unit test failure: is it good practice? assume you have a unit test that contains these lines assertNotNull(someVal); assertNotEmpty(someVal); This obviously checks that someVal is not null and is populated with something. The question is, is the first line necessary and does it add anything to the test? Should we not just have the second line, and if it's null it will throw a null pointer exception which still indicates a failing unit test (but not a failing assertion). What's the best practice in such simple cases?
I'm not a big fan of `assertNot()`'s and more generally testing unexpected things that could happen to the SUT, let alone testing them in addition to the normal Assert in every single test. IMO you should only test for nominal states of your objects. If it _is_ normal for `someVal` to be null _in some circumstances_ , then create a dedicated test method checking that it is indeed null in that scenario. Choose an intention-revealing name for your test, like `someValShouldBeNullWhen...()`. Do the same for empty, or any other value. You see that unexpected things happen to your SUTs by looking at your tests exception messages, not by trying to forecast each of these unexpected things in advance and cramming your tests with assertNots for them.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 6, "tags": "java, unit testing, junit, tdd, testng" }
Publishing website created using asp.net I have created a website with asp.net and uses oracle connectivity with pl/sql developer.i have uses the crystal report which is a third party tool. how to purchase it. i am using visual studio 2005 and yes i am using basic crystal crystal that comes with visual studio. Now suppose i hav purchase a domain www.abc.com. and i want to pubsite it. i have uses the crystal report which is a third party tool. how to purchase it. plz give a expert advice. Thankyou.
Generally when you publish a website that makes use of Crystal Reports, the necessary DLLs are/must be included in the package you deploy on your webserver. Read these pages for more details: Deployment Components Features of Crystal Reports for Visual Studio How to deploy the Crystal Reports 2008 Basic Runtime
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "asp.net, deployment, crystal reports" }
JPEG 200 (aka J2K) handling in Silverlight app - any suggestions? I need to handle JPEG 2000 (aka J2K) images in my silverlight app. Files stored either in the DB or file system on the server. Any suggestions how to handle them on the client? The only working converter I came across was written in Java. There are some ports to J#, but most likely they are not going to work on the client. The requirement is that the conversion should happen on the client to conserve the bandwidth and speed up the streaming of huge images.
It's not supported by Silverlight and .Net Image Tools don't support it too at the moment. So you have to write your own, port the (Java) version or ask the ImageTools developers if they can help you.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "silverlight, jpeg2000" }
ms access before change macro not working I am trying to use Microsoft Access data macro: `IF [Dataset_Used]='VS' And IsNull([VS_File]) Then` RaiseError Error Number: 4002 Error Description: Please choose a VS file Above macro is working. But if I add `And [Note]<>'no file'` to the If condition `[Dataset_Used]='VS' And IsNull([VS_File]) And [Note]<>'no file'`, the macro will not work. Working means the error description will be displayed when If condition is met.
Try this condition: And Nz([Note])<>'no file' Quite sure `[Note]` field contains mostly Nulls. Null is a special case, `Null <> "something"` equals Null, not True or False. `True And Null` gives also Null. But `True Or Null` gives True.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ms access" }
D2: Function Pointers won't compile I'm trying to use function pointers in DLang (Pointer to function), but it wont compile. All the code on the web on making function pointers, doesn't work for me. This is my code: tqvar function(tqlist)[string] procs; procs["divide"] = &divide;/// cannot implicitly convert expression (&this.divide) of type tqvar delegate(tqlist args) to tqvar function(tqlist) (QScript) tqvar divide(tqlist args){ tqvar result; result.ii = true; result.d = args.read(0).d/args.read(1).d; return result; }; I'm using dmd2, on ubuntu.
`divide` is apparently a delegate, not a function. You can either use a list of delegates instead (just replace `function` with `delegate`) or ensure your function is not a delegate. For the latter: it looks like divide is a class method, not a plain function. Either make it `static` or move it outside of the class body.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "pointers, d" }
Regex - How do I get this value from a line of a text file? I'm so very poor at preg_match, which I think is the function required here. I'm trying to get the time value (always 3 decimals I think) from this line in a text file:- frame= 42 q= 38.0 f_size= 909 s_size= 1kB time= 1.400 br= 218.2kbits/s avg_br= 5.2kbits/s type= I So, in that example I want to get 1.400. Any guidance much appreciated, I find regex truly, truly baffling.
if(preg_match('/time\s*=\s*(\d+\.\d{3})/',$str,$matches)) { $time = $matches[1]; } Just incase you are not sure about the number of decimal digits or the existence of the decimal point you can do: if(preg_match('/time\s*=\s*(\d+\.?\d+)/',$str,$matches)) { $time = $matches[1]; } See it
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "php, regex, string, preg match" }
Jquery complaining syntax error - Json coming from a asp net mvc controller From this call @using (Ajax.BeginForm("Manage", "Account", new AjaxOptions { HttpMethod = "POST", Confirm = "Você tem certeza que deseja salvar a alteração?", OnSuccess = "close" })) the OnSuccess function is called and execute the following: function close(json) { $('"#' + json.param1 + '"').dialog("close"); alert(json.Message); } and I get this error: Error: Syntax error, unrecognized expression: "#UserSettings" [Break On This Error] throw new Error( "Syntax error, unrecognized expression: " + msg ); `$('#UserSettings').dialog("close");` works fine so I don´t get why the error.
You do not need the extra double quotation marks in your jQuery selector. It should be: $('#' + json.param1).dialog('close');
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "jquery, asp.net mvc, model view controller" }
Change fontSize and text in tag using only one JavaScript function I am trying to change the `fontSize` and `innerText` using the same JavaScript function. I've changed the `fontSize`, but I also want to change the text inside the `<h3>` tag with the same JavaScript function. Is that possible? <h3 id="h3_heading">This is H3 HEADING Click Below Button to Change Font Size</h3> <button type="button" onclick="document.getElementById('h3_heading').style.fontSize ='72px'""> Click me to change font size and Written Text Inside H3 Tag </button>
Sure is, you'll need to change your onclick to point to a function in your javascript code i.e. <script> function changeFontSize(elementId) { var element = document.getElementById(elementId); element.style.fontSize = '72px'; element.innerText = 'Text you want here'; } </script> Your onclick would change to `onclick="changeFontSize('h3_heading')"`
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "javascript, function" }
Controlling scatterhist bar colors I was trying to make the bars in my `scatterhist` plot be of the same color as the markers: x = randn(1,20); y = randn(1,20); myColour = [1 0 0]; % red scatterhist(x, y, 'Color', myColour); mygca = get(gca,'children'); set(mygca,'markerfacecolor', myColour); However, the bars are of a slightly different color, namely a reddish hue, [249 96 96]: ![enter image description here]( The Scatterhist documentation seems to suggest bar colors just follow marker color, which in this case does not happen. How can I control color of the `scatterhist` bars, on MATLAB R2016a?
This happens because the bars have an **alpha** (transparency) setting. To fix this, make sure the `'FaceAlpha'` setting is set to 1. For example: x = randn(1,20); y = randn(1,20); myColour = [1 0 0]; hSh = scatterhist(x, y, 'Color', myColour); hSh(1).Children.MarkerFaceColor = myColour; hSh(2).Children.FaceAlpha = 1; hSh(3).Children.FaceAlpha = 1; Which yields: ![Proper colors](
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "matlab, plot, colors, histogram, scatter plot" }
Excel - RIGHT formula not working as expected ![RIGHT formula]( I am trying to get the last 4 characters (the year in this case) from one column to be displayed in a new column. As far as I am aware, the formula I am doing is correct but the column isn't displaying the correct values (should be 2016, 2015 etc)
So first, use right() for each cell: =right(H2,4) Then get excel to recognize the result as a number not text (text is left and numbers right formatted in the cell): =right(H2,4)*1 or =value(right(H2,4)) But, as others have pointed out, dates are represented in Excel with a serial number - try changing the formatting and you will see.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "excel, date, excel formula, formula" }
Is finally block really necessary for the clean up code (like closing streams)? I am very confused as to why do I need to need to put the clean-up code like closing streams in a `finally` block. I've read that the code in `finally` block will run no matter what (whether there's an exception); and after the `finally` block runs, the rest of the method continues. My question is: if the rest of the method has to continue then why don't I put the clean-up code after my try/catch block in a function?
The finally block will always run if an uncaught exception is thrown, but the rest of the code in the method will be skipped. So if you put clean-up code after the finally block, it won't get called if there is an exception.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 8, "tags": "java, exception, try catch finally" }
Regex for splitting a string with some conditions in PHP this is my problem, I'm not very good with regular expressions, I need split a string in this way, for example I have this string: 1002;string1<br> string2<br> string3 1003;string1<br> string2<br> string3 So I need to split the whole string in this way: separating each item block, in the above case: one of them would be: 1003;string1<br> string2<br> string3 I've tried to split by `$data = explode("\n", $string);` but it separates each line, and I want to ignore if the `\n` is preceded by `<br>`, I suppose I have to use regular expressions, maybe using the `preg_split()` function? Thanks in advance
You can use: $matches = preg_split('/(?<!<br>)\n/', $input); RegEx Demo This will split the input when `<br>` is not there before `\n`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, regex, regex negation" }
I want to draw a thin line on my view as shown in the images i linked ![]( ![]( The images explain what I want vs what I'm getting. Here is my code. func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) { let path = UIBezierPath() path.moveToPoint(start) path.addLineToPoint(end) //design path in layer let shapeLayer = CAShapeLayer() shapeLayer.path = path.CGPath shapeLayer.strokeColor = lineColor.CGColor shapeLayer.lineWidth = 0.22 view.layer.addSublayer(shapeLayer) }
let lineView : UIView = UIView(frame: CGRect(0, 20, self.view.width, 2) lineView.backgroundColor = UIColor.blackColor.colorWithAlphaComponent(0.2)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "swift, line" }
What is Java Regex for checking "Must contain English Alphabets & Can contain either Digit /Dot/ Hyphen/ Space"? I want to check if a name field meets these requirements: -Must contain English Alphabets -Can contain either Digit /Dot/ Hyphen/ Space LuckStar12 : valid Batman : valid LuckStar-12 : valid LuckStar.1 - 2 : valid Luck Star 5 : valid 21212 : not valid cos it doesn't contain any English Alphabets autó : not valid cos it contain "ó" ----- : not valid cos it doesn't contain any English Alphabets This `"[a-zA-Z0-9\\s.-]+"` is to check if the name field has chars fall into these English Alphabets/ Digit /Dot/ Hyphen/ Space. However, it doesn't force "Must contain English Alphabets". I tried `(?=.*[a-zA-Z])[0-9\\s.-]` but it doesn't work. So What is Java Regex for checking "Must contain English Alphabets & Can contain either Digit /Dot/ Hyphen/ Space"?
You could make use of a lookahead assertion: ^(?=.*[a-zA-Z])[a-zA-Z0-9. -]*$
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, regex, validation" }
.htaccess redirect main domain but not sub subfolder I was wondering how to exclude a subfolder from .htaccess redirect. I have an .htaccess file in the root of my old domain and I have the following in it: Options +FollowSymLinks RewriteEngine on RewriteRule (.*) [R=301,L] This of course redirects any traffic from the old domain to the new one. But I want to exclude a directory from this rule. Meaning www.olddomain.com/media/videos should not redirect to www.newdomain.com/media/videos The reason I want the exclusion is because I'm hosting static files such as videos on a shared web server (old domain) and I'm keeping everything else the site needs on the new VPS server (new domain).
Just put `RewriteCond %{REQUEST_URI} !^/media/videos` above your RewriteRule. It checks wether the URL starts with `/media/videos` and if it does so, the RewriteRule will not be met.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": ".htaccess, redirect, vps" }
Обработка нажатия клавиши C# Как обработать событие по нажатию клавиши (например, в текстбоксе), чтобы при попытке ввода символа "|" ничего не происходило?
Фильтруйте ввод в OnKeyPress: public class FilteredTextBox : TextBox { protected override void OnKeyPress(KeyPressEventArgs e) { if (e.KeyChar == '|') { e.Handled = true; return; } base.OnKeyPress(e); } } Имейте в виду, что ввести запрещенный символ можно не только напрямую, набирая его на клавиатуре, но и вставив из буфера обмена. Думаю, целесообразно было бы использовать ту же логику, что и в стандартном NumericUpDown (посмотрите исходники).
stackexchange-ru_stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c#, клавиши" }
Hive and selecting non matching records I have two table like table A , B , i need to select non matching records of A with B ( that is A minus B ) . A is having multiple columns and B is single column( ID) . I have tried like below but it is taking too much time Select * from A where A.ID <> ( select B.ID from B). And also I have tried Select * from A left outer join on B where A.ID = B.ID AND B.ID IS NULL It's showing me wrong result Please help me to identify solution to this . Thank you .
use where clause to filter. Select * from A left outer join B on A.ID = B.ID where B.ID IS NULL
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "sql, hadoop, mapreduce, hive, hiveql" }
How do I open a temporary file AND get its filename? I need to create a temporary file in my C program, write some data to it, and then invoke an external command (via exec or system) to do some processing on the file I just created. I did not write the external command nor is it feasible to integrate it into my program so I don't think I can share an already open descriptor with it. Therefore, I need to know the name of the temp file created. The tempname() function does this, but unfortunately it recommends that you don't use itself, due to a possible race condition between getting the name and opening the file, and neither of the functions it recommends (tmpfile and mkstemp) provide a way to find out the actual name of the file created.
It is not true that `mkstemp` does not let you know the temporary file name, try to compile and execute this program to see yourself: #include <stdlib.h> #include <stdio.h> int main() { char fn[] = "/tmp/fileXXXXXX"; int fd = mkstemp(fn); char cmd[200]; int n = snprintf(cmd, sizeof(cmd), "ls -l %s\n", fn); printf("snprintf=>%d\n sizeof(fn)=%d\n", n, sizeof(fn)); // extra info, see comments printf("%s\n", cmd); return system(cmd); } `mkstemp` will replace the file name template in the buffer you pass to it with actual file name, you can do whatever you want with this buffer later on.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 5, "tags": "c, file, posix, temp" }
How to run and navigate the menu at the same time with controller? How to use controller to navigate the menu while runing (i.e. not walking, but dashing)? For example, in this Dark Souls 3 speed run video the guy simultaniously runs and navigates the menu. Note how his stamina decreased while he was in the menu - that means that he runs, not just walks. I'm sure he uses a controller, like all speed runners do. I tried to figure out how he does it and failed. Here is controller controls for DS3. Theoretically, you can press all the buttons with 3 fingers if you claw the controller. But in practice, you have a conflict due to B button: 1. To run you must press left stick (move) and **B button (dash)** simultaniously. 2. To navigate menu you must press the menu button (entry the menu), A (accept) and **B (back)** buttons and D-pad (navigate). Therefore, when I try it, I stop running and start walking right when I press menu button (while holding left stick and B).
As @SGR suggested, it must be so called "auto-run". One can switch between walking and running by pressing a button on a keyboard. For example, at DS2 it is "X" button. So you: 1\. Run by holding Left stick + B on controller. 2\. Press X on keyboard. 3\. Stop holding B on controller and operate in menu. 4\. Once you've done - hold B. 5\. Press X on keyboard. I'm sure this is the case, because I've found the DS2 speed run video of the same guy. And DS2 shows auto run status under hp-bar.
stackexchange-gaming
{ "answer_score": 0, "question_score": 4, "tags": "controllers, dark souls 3, speedrun" }
Configuring Geth node started by Mist When I launch mist, it starts up a geth node by default. How do I specify the configurations for this node? Specifically, I just want to achieve the equivalent of `geth --cache=1024` which I can do via a CLI prior to launching the mist GUI.
Mist now accepts new options that can be passed to the underlying node, which by default is `geth`. You can use all the same options from the node, you just need to prefix them with `--node`. For instance, the `geth` option `--datadir` becomes `mist` option `--node-datadir`. My mist launcher looks something like this: mist --node-cache 512 --node-maxpeers 50 --node-port 30304 On linux, you can see your options were used to launch geth with a command like the following: ps aux | grep geth
stackexchange-ethereum
{ "answer_score": 2, "question_score": 2, "tags": "go ethereum, mist" }
Is this algebraic identity obvious? $\sum_{i=1}^n \prod_{j\neq i} {\lambda_j\over \lambda_j-\lambda_i}=1$ If $\lambda_1,\dots,\lambda_n$ are distinct positive real numbers, then $$\sum_{i=1}^n \prod_{j\neq i} {\lambda_j\over \lambda_j-\lambda_i}=1.$$ This identity follows from a probability calculation that you can find at the top of page 311 in the 10th edition of _Introduction to Probability Models_ by Sheldon Ross. Is there a slick or obvious explanation for this identity? This question is sort of similar to my previous problem; clearly algebra is not my strong suit!
It's the Lagrange interpolation polynomial for the constant function $1$ evaluated at $0$: $$\sum_{i=1}^n 1 \prod_{j\neq i} {{\lambda_j-0}\over \lambda_j-\lambda_i}=1$$ In general, you have that the polynomial below interpolates the data points $(\lambda_i,y_i$): $$\sum_{i=1}^n y_i \prod_{j\neq i} {{\lambda_j-x}\over \lambda_j-\lambda_i}$$ See <
stackexchange-math
{ "answer_score": 31, "question_score": 24, "tags": "algebra precalculus, summation, products" }
I can't install this repository I need to install a python package like so: pip install But when trying I get the error ERROR: Cannot unpack file C:\Users\lolo\AppData\Local\Temp\pip-unpack-7zvkgwjf\082405ec4ccb9dd454521b266d5ef04d520c703b (downloaded from C:\Users\lolo\AppData\Local\Temp\pip-req-build-sq3hhdbf, content-type: text/html; charset=utf-8); cannot detect archive format ERROR: Cannot determine archive format of C:\Users\lolo\AppData\Local\Temp\pip-req-build-sq3hhdbf I don't understand this error. Please help
You could try installing the archive for the commit rather than the diff between it and another commit. To download a zip for a commit from github, you can use the following URL: ` In your example, you could use `pip install to install the package.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python, python 3.x, kivy, kivy language, kivymd" }
¿Cómo puedo saber los comandos que ha usado un usuario durante una sesión en linux? He investigado que mediante el comando **journalctl** se podría obtener esa información. Pero... he almacenado la información que me otorga en un archivo y busque para saber si existía alguna coincidencia con algún comando que había usado recientemente y no he encontrado nada, cabe mencionar que mi distro es arch linux me podrían ayudar porfavor.
Una buena opción es consultar el history del bash, independientemente de la distro Dependiendo el que uses será .bash_history, .zsh_history, etc. Otra opción es usar el comando history.
stackexchange-es_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "linux" }
Use a person's name to create a unique, non-reversible ID Is there a way (an algorithm) to take someone's name (first name and surname) and turn it into a unique, non-reversible ID? I know I could just start at unique id = 1 and just add one. I was wondering if there was a way that I could generate IDs using someone's name. I'm just after a pointer to the way to do it and I'll code it myself.
What you're asking for is called a _hash function_. Hash functions will always produce the same fixed-length output for a given input. For non-cryptographic endeavours, SHA256 is often a good choice. It will produce a 256-bit output and is available natively in most standard libraries.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "encryption, cryptography, statistics" }
Is it correct to dynamically add rows to a table (in sqlite), or should I use csv? Just like when adding a new contact in the ios contact app, (like this) you can add multiple phone numbers, and it doesn't know how many there will be, so therefore they don't know how many rows they should initially add in the table of `sqlite`. So how does that work, do they dynamically add rows to the table, or do they use csv? (I'm using objective c)
You have one table for the contacts: CREATE TABLE contacts( id INTEGER PRIMARY KEY, name VARCHAR(50) ); and you link multiple rows in a separate table to the contacts CREATE TABLE phone_numbers( id INTEGER PRIMARY KEY, phone_number VARCHAR(15), contact_id INTEGER REFERENCES contacts(id) ); When you create a contact, you add a row to contacts. When you add a phone number, you add it to phone numbers and refer to the row in contacts. You can add as many rows as you want to phone numbers for the same contact.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sqlite, csv" }
Unity equivalent for Ninject's Bind.ToMethod of IPrincipal,IIdentity I'm trying to replicate the following Ninject syntax in Unity, but not having any luck: Bind<IIdentity>().ToMethod(c => HttpContext.Current.User.Identity); I'm thinking it ought to look something like: IUnityContainer container; ... container.RegisterType<IIdentity>(HttpContext.Current.User.Identity); How should it be?
While neontapir's answer could work, that extension method is Obsolete. The correct way to do this now would be to use an InjectionFactory: container.RegisterType<IIdentity>(new InjectionFactory(u => HttpContext.Current.User.Identity));
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 6, "tags": "c#, .net, unity container, ninject, iidentity" }
Conformal mapping on unit disk Let $\mathbb{C}_{-}^r:=\mathbb{C}\setminus(]-\infty,-\frac{1}{r}])$, $~\mathbb{C}_{-}:=\mathbb{C}\setminus(]-\infty,0])$, $~\mathbb{D}:= \\{z\in \mathbb{C}\mid |z|<1\\}$ and $\mathbb{G}=\\{z\in \mathbb{C}\mid Re(z)>0\\}$ I have to find a conformal map from $\mathbb{C}_{-}^r$ to $\mathbb{D}$ for any $r>0$ My try: 1. Apply translation $f_{1}(z):= z+\frac{1}{r} \Rightarrow f_{1}(\mathbb{C}_{-}^r) = \mathbb{C}_{-}$ 2. Apply $f_{2}(z)=\sqrt{z} \Rightarrow f_{1}(\mathbb{C}_{-})=\mathbb{G}$ 3. Apply $f_{3}(z)=\frac{z-1}{z+1} \Rightarrow f_{1}(\mathbb{G})=\mathbb{D}$ Therefore the conformal map $$f(z)=(f_{3} \circ f_{2} \circ f_{1})(z)=\frac{\sqrt{z+\frac{1}{r}}-1}{\sqrt{z+\frac{1}{r}}+1}$$ but the official answer is $$f(z) =\frac{\sqrt{rz+1}-1}{\sqrt{rz+1}+1}$$ What am I missing ?
The mapping $\varphi (z) =r\left(z+\frac{1}{r} \right)$ is also a biholomorphic mapping from $\mathbb{C}^r_- $ onto $\mathbb{C}_- $. So both the answers are good.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "complex analysis, conformal geometry" }
Get notified when cursor position changed in Eclipse TextEditor I am developing a plugin to eclipse and I want to add some actions to the context menu. But actually I wanted to prepare results beforehead according to the text selection in the editor and just show them when the menu item will be selected. I followed that article < \- all interfaces (`ISelectionListener`, `ISelectionChangedListener` etc) allow to handle the `SelectionChanged` event, but editor counts changing only when length of selection also changes - so the simple click in the editor doesn't fire the event, although I want to get the word (for example) as a selection if cursor is inside the word now and lenght is 0. So the question is - what is the simpliest solution for traking down cursor position/offset/selections with zero lengh value changing?
In that case you have to use KeyListener and MouseListener as well. For e.g take a look at org.eclipse.jface.text.PaintManager, and it listens to all these events.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "eclipse, eclipse plugin, selectionchanged" }
jQuery update DOM to access injected html tags Ok I'm submitting a form via ajax. The result string is a bunch of html links and images which I append to the body of the DOM. Is it possible to search with jQuery within this new code? before ajax request: <div id="results"></div> after ajax request: <div id=results"> <img src="somevalidpicture.jpg" class="image"/> <img src="somevalidpicture2.jpg" class="image"/> </div> How can I run my jQuery code to manipulate that code again? For example: $(".image").show(slow); I suspect I cannot access the .image class, because it wasn't there when the page first loaded. And it doesn't show up in the sourcecode (browser). Is there a way to refresh/update the DOM?
You _can_ access them, as soon as the elements are added to the DOM `$(".image")` will find them. However `slow` needs to be in quotes for your particular example: $(".image").show("slow"); `"show"` is a key that means 600ms, `$(".image").show(600);` would have the same effect. * * * Don't use "View Source" to see what's currently in your page (since it'll show what was there when the page loaded), instead use a DOM inspector like Firebug or the Chrome Developer tools.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "dom, jquery" }
Time complexitiy: Which is slower? (O(N^3) or O(2^N)) I'm learning time complexity recently and just wondering which Big-O Complexity is slower O(N^3) or O(2^N)? And why would you say that? I can find a lot of information compared to O(N^2), O(2^N) but not O(N^3). Thank you.
Changes to the "power" has greater effect than changing the "base", unless base is close to one (floating point 1.00001f). So slowness is wildly increasing when N>2 because of N being power in the O(2^N)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "time complexity" }
Does Qt have a "XAML-like" markup-based GUI creation? WPF uses XAML. Gtk has GladeXML, and associated tooling. Does something similar exist for Qt? Just to clarify: I'm asking about runtime loading of a UI from a markup file. XML/YAML/JSON, etc. Thank you
The .ui files created by Qt's Designer application can be loaded at runtime for a dynamic UI. It will allow the UI to be changed, but it doesn't allow state information like QML does. Also, if you want to do much with the UI, you need to know some information about the widgets in the .ui file.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "qt, xaml, qt4, glade, wxglade" }