INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to represent -infinity in programming How can I represent `-infinity` in C++, Java, etc.? In my exercise, I need to initialize a variable with `-infinity` to show that it's a very small number. When computing `-infinity - 3`, or `-infinity + 5` it should also result `-infinity`. I tried initializing it with `INT_MIN`, but when I compute `INT_MIN - 1` I get the upper limit, so I can't make a test like: `if(value < INT_MIN) var = INT_MIN;` So how can I do that?
You could define a number as -infinite and, when adding or substracting something from a number, you do first check if the variable was equal to that pseudo-number. If so you just leave it as it was. But you might find library functions giving you that functionality implemented, e.g Double in Java or std in c++.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "algorithm, infinity" }
R create new data.frame from old one according to column values I have this simple data.frame x=c(1,2,3,4,5,6) y=c(5,6,1,2,4,5) z=c(1,1,1,2,2,2) data=data.frame(x,y,z) I want to get data1= x y z 1 1 5 1 2 2 6 1 3 3 1 1 and data2= x y z 4 4 2 2 5 5 4 2 6 6 5 2 accordig to Z values
Try this split(data, z) this is a list
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "r" }
Kill all process which uses specified port on Ubuntu 14.04 What's the reason the process is still alive? List of node process running and what I tried: root@111:/home/ubuntu# ps -e -o pid,ppid,stat,cmd | grep node 3150 1 Ss sudo /usr/bin/node /home/ubuntu/chatapp/bin/www 3152 3150 Sl /usr/bin/node /home/ubuntu/chatapp/bin/www 4407 1558 S+ grep --color=auto node root@111:/home/ubuntu# kill -9 3150 root@111:/home/ubuntu# kill -9 3152 root@111:/home/ubuntu# ps -e -o pid,ppid,stat,cmd | grep node 4665 1 Ss sudo /usr/bin/node /home/ubuntu/chatapp/bin/www 4667 4665 Sl /usr/bin/node /home/ubuntu/chatapp/bin/www 4680 1558 S+ grep --color=auto node
Try with: $ sudo kill -9 18200 Note the added flag '-9', which forces the murder... From linus signal(7) man page: ... SIGKILL 9 Term Kill signal ...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "node.js, port, ubuntu 14.04, amazon ec2" }
Code example with annotation in JavaDoc my JavaDoc doesn't work when I have a code example with an annotation. Any suggestions? /** * <pre> * public class Demo { * @DemoAnnotation * public void demoMethod() { * } * } * </pre> */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface DemoAnnotation {
You must replace `@` with `&#064;` in your JavaDoc.
stackexchange-stackoverflow
{ "answer_score": 35, "question_score": 36, "tags": "java, javadoc" }
How to add floating action button one by one in Linearlayout I'm developing an attendance manager app. To take attendance , I've to create layout like this ![enter image description here]( I want to make it programatically. In the below layout I've used to add FAB using xml.
You can use a RecyclerView with a GridLayoutManager to achieve that programatically, here some example: < < Hope this helps.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "android, android linearlayout, floating action button" }
Spring constructor autowiring and initializing other field I having a Spring class, where I am autowiring a service using constructor, plus in the same constructor I am intializing other field of the same class. @Component class Converter { private TestService testService; private Interger otherFields; @Autowired public Converter(TestService testService) { this.testService = testService; this.otherFields = new Integer(10); } } My Functionality is working fine, but is it a good practice?, would `@Autowired` annotation have any impact on `otherFields` intialization process
It shouldn't. Back in the xml days, when you want to pass on an argument to a constructor, you mentioned your ref bean for the constructor arg. This just means that you must have a constructor that takes the specified bean type as an argument. It doesn't really matter what you add in the constructor, as long as you are creating a valid object through the constructor (though this is just normal java programming and nothing to do with Spring). Auto-wiring is just an easy way to create your object with the necessary dependencies and your code is still your code.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "java, spring, dependency injection" }
Flat Array depth nesting I am trying to nest a flat array to represent an incremental depth level sequence as follows: `['1'['2'['3'['4'['5']]]]]` from a given string `'1/2/3/4/5'` so far I have managed to achieve to `[ '1', '2', '3', '4', '5' ]` from `str.split('/')`
Split the string into an array on "/" then reduce it, right-to-left to a new array where each iteration creates a new array with the number at the start followed by the previous iteration result. const str = "1/2/3/4/5" const arr = str.split("/").reduceRight((inner, num) => [ num, [].concat(inner) ]) console.info(JSON.stringify(arr)) .as-console-wrapper { max-height: 100% !important; } References: * `Array.prototype.reduceRight()`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "javascript, arrays" }
How do I zoom in / zoom out in Adobe Flash? I am using Adobe Flash CS6, and I am having troubles with the zoom feature in the editor. I am aware that there is a drop down menu where you can select the zoom level you want, but that is not usable at all. I need to be able to zoom in/out using my mouse wheel. Pressing an extra button is no problem, as I use CTRL+mouse wheel all the time in other applications. But in Flash, it seems you can only zoom in/out with the drop down menu. Is there any way to get Adobe Flash to use the mouse wheel to zoom? Or is there already a keyboard shortcut I'm not aware of?
If you are using windows: In flash one must hold SHIFT and CTRL (CTRL + SHIFT + mouse wheel), which doesn't really make sense since in all the other adobes softwares zooming works with ALT+ mouse. Maybe flash is just the weird one :P If you're using Mac: Sorry, no clue Source: Went through same dilemma.
stackexchange-superuser
{ "answer_score": 3, "question_score": 1, "tags": "mouse, flash, zoom, flash cs6" }
what is the best practice to reload AngularJS page I need to know what is best practice to work with Auth Service and authInterceptor Service $window.location.reload(); $scope.$apply(); $location.path('/');
I have used this in my application to rerender the data.if you are in the same state as well you will be able to rerender the data. `$state.transitionTo('app.emp.nav.portfolio', null, {'reload':true});`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, angularjs" }
Weather widget in your app? So I'm working on an app and I'd like it to have a Weather Widget inside of one of my Linear Layouts. It this possible? I have searched the web and didn't find any useful answer for my question. So please help! If you know how, post some code or something. Thanks!
Have a look at this tutorial. This is easy to use: link
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "android, android widget, widget, weather" }
Dynamic page titles in Symfony 1.4 I'm wondering if anyone's got any good advice/experience regarding setting dynamic meta titles in Symfony? Currently, the solution I'm aware of would be to use the following code to set a title individidually in each action: $this->getResponse()->setTitle('This is a title'); Because I also need translated titles, I could call the i18n helper in the action to get them included in the extracted XLIFFs. No special SEO stuff needed, just a clean title. However, the above does require that I tweak every single action separately. View.yml is not suitable as I frequently have multiple actions/templates per module. Is anyone aware of a better approach in Symfony or is this indeed the right/only way to go? Thank you.
I think writing separate titles in every action is OK. But if you want to add some global prefix you can use something like this in layout: <title>SITE NAME — <?= $sf_response->getTitle() ?></title> Also you can probably manipulate a title per module using preExecute() method in actions.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 8, "tags": "symfony1, metadata, response, action, title" }
How to sleep one thread while other threads is working in visualC#? I want to make two threads like `thread1` and `thread2` and individually control them but when I do `thread1.Sleep(1000)`, it gives an error. > Member 'System.Threading.Thread.Sleep(int)' cannot be accessed with an instance reference; qualify it with a type name instead How can I do this?
Call the Thread.Sleep(1000) in the function that is being executed by thread1. For example you have : Thread thread1 = new Thread(MyFunction); thread1.Start(); than in MyFunction call the Thread.Sleep(1000);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, multithreading" }
Fiddling with a Fibonacci-Like Sequence Let $X\in\mathbb{Z}.$ Let $F_n$ be a sequence of positive integers given by $$F_{i+1}=F_i+F_{i-1}$$ $$F_2=X*F_1+F_0$$ I am trying to find an upper bound or (sharp) inequality of $F_i$ in terms of $F_1$ and $F_0$. If $F_{i+1}=F_i+F_{i-1}$ for all $i$, then substituting $F_i=q^i$ gives $F_i=(\frac{1+\sqrt{5}}{2})^i$. In our case, $$F_j= (\frac{1+\sqrt{5}}{2})^j+(XF_1+F_0)-(F_1+F_0)= (\frac{1+\sqrt{5}}{2})^j+(X-1)F_1 \,\,(*)$$ Is the first equality in $(*)$ correct?
The general solution of $F_{i+1}=F_i+F_{i-1}$ is $F_j=A\phi^j+B\overline\phi\,^{j}$ where $\phi=(1+\sqrt5)/2$ and $\overline\phi=(1-\sqrt5)/2$, and $A$ and $B$ are determined by the initial conditions. In your case the initial conditions are $F_1=F_1$ and $F_2=XF_1+F_0$. So you can substitute in $i=1$ and $i=2$ to get two linear equations for the two unknowns $A$ and $B$, and then you'll have your equation for $F_j$.
stackexchange-math
{ "answer_score": 5, "question_score": 0, "tags": "recurrence relations, fibonacci numbers" }
Hyperledger Fabric with docker not storing data after restart I setup Hyperledger Fabric V0.6 with docker image. I wrote small chain code program and perform some operations. Data is getting stored and fetched on request from Hyperledger blockchain. I restart my chaincode program and data still persist. Ofcouse this should be expected behaviour. But when I stop my Hyperledger fabric with command docker-compose down and start it again with docker-compose start and then start my chaincode program, I found that the whole data which was written before restart is gone. I couldn't find any data in my blockchain. How can I avoid this behaviour of Hyperledger? I am running it on single peer/node. With multiple peers, if one of the peer restarted, then data/transactions from other peers get copied on it. But consider a worst scenario when all peers down. Does that mean we loose all our data?
As per the official docs `docker-compose down` stops and **removes** all containers listed in docker-compose file _along_ with their volumes (unless specified as external, have a look into the documentation). You may want to stop the containers with `docker-compose stop` \- this way after `docker-compose up` their data will be preserved.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 7, "tags": "docker, docker compose, blockchain, hyperledger, hyperledger fabric" }
Make zsh history search behave like bash reverse-i-search * In **bash** , pressing `[CTRL]+[r]` will open the `reverse-i-search` prompt. * How can I **search the zsh history** in a similar way? _Note:_ The search query will **hit the middle of the full command** only, **instead of match at it's beginning** as required by the normal zsh search.
To make **zsh behave like bash** when pressing `[CTRL]+[r]`: # for non-pattern search like in bash bindkey "^R" history-incremental-search-backward` or # for pattern search (the wildcard `*` will use zsh completion) bindkey "^R" history-incremental-pattern-search-backward * * * **Note:** Add the line to your `~/.zshrc` to make it permanent.
stackexchange-superuser
{ "answer_score": 3, "question_score": 4, "tags": "bash, search, zsh, command history" }
Where do you report typos at developer.android.com? I found a typo on the guide section at developer.android.com, but I can't find a link/email to report the typo to. I don't want to report it on the Android Developers Google group, as its a typo and not a technical question. Anyone have an email address or link I can use to report typos?
Take this with a grain of salt, but I _think_ you can report typos on the Google Code page. If you search the issue tracker for "typo" you get a bunch of other hits, some of which were fixed or followed-up on, and they all seem to at least be marked 'Medium' severity. I also saw this archived android-developers post, where someone suggested to open a ticket on the tracker, but I don't think the poster is a Google employee or anything.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "android" }
Output a repos URLs using Octokit.rb I'm attempting to list details of a Github accounts repos using Octokit.rb, but can't seem to find the associated URLs. In the first instance all I need to do is authenticate with the Github API using OAuth and output the details to the console. Here's a basic example so far: client = Octokit::Client.new :access_token => 'my_token' client.repos.each do |repo| puts repo.name puts repo.description # html_url & clone_url go here. end I'm sure I've overlooked something obvious, but what do you need to do to find the `html_url`, `clone_url` etc (as per the API) for each repository?
Turns out it was obvious after all: client = Octokit::Client.new :access_token => 'my_token' client.repos.each do |repo| puts repo.name puts repo.description # find the urls puts repo.rels[:html].href puts repo.rels[:git].href puts repo.rels[:clone].href puts repo.rels[:ssh].href end
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 6, "tags": "ruby, github api, octokit" }
How to find out the equation whose roots are trigonometric? Find out the equation whose roots are $\sin^2 (2\pi/7), \sin^2 (4\pi/7), \sin^2 (8\pi/7)$. I wanted to solve this by firstly finding the equation ,the roots of which are $\sin 2\pi/7,\sin 4\pi/7, \sin 8\pi/7$ .Then i would find the equation wanted in the equation by using $Y = x^2$ or, $X = Y^1/2$; $X$ is the root of the 2nd equation i.e. $\sin 2\pi/7\ldots$ & $Y$ is the root of 1st equation. Now i would put the value of $X$ in the 2nd equation i.e. $Y^1/2$ & wld get the equation required. But i don't know how to find an equation whose roots are trigonometric. Plz help.
Like factor $z^7-1$ into linear and quadratic factors and prove that $ \cos(\pi/7) \cdot\cos(2\pi/7) \cdot\cos(3\pi/7)=1/8$ or Prove that $\frac{1}{4-\sec^{2}(2\pi/7)} + \frac{1}{4-\sec^{2}(4\pi/7)} + \frac{1}{4-\sec^{2}(6\pi/7)} = 1$ $\displaystyle z^3+z^2-3z-1=0\ \ \ \ (1),$ has the roots $\displaystyle 2\cos\frac{2\pi}7, 2\cos\frac{4\pi}7, 2\cos\frac{6\pi}7$ Now using $\displaystyle\cos2A=2-\sin^2A\iff\sin^2A=\frac{1-\cos2A}2,$ $\displaystyle\sin^2\frac{8\pi}7=\dfrac{1-\cos\frac{16\pi}7}2$ and again$\displaystyle\cos\frac{16\pi}7=\cos\left(2\pi+\frac{2\pi}7\right)=\cos\frac{2\pi}7$ etc. Can you take it home form here? See also: Prove that $\cot^2{(\pi/7)} + \cot^2{(2\pi/7)} + \cot^2{(3\pi/7)} = 5$
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "trigonometry" }
How is Fuel needed to be consumed calculated when MTOM and Actual Mass is known I'm practicing for my EASA PPL(A) exams and one of the questions I came across looks like this: > How much taxi fuel must be consumed before take-off to reduce the aircraft mass to the maximum take-off mass? > > Maximum ramp mass (MRM): 1150 kg > Actual ramp mass: 1148 kg > Maximum take-off mass (MTOM): 1145 kg (1,00 P.) > > > Possible answers: > > * 2L > * 3L > * 5L > * 4L > Now, my thinking was Fuel needed to be consumed = Actual ramp mass - MTOM => 3L But it seems the correct answer is 4L. I don't understand why.
Your thinking is correct, the fuel needed to be consumed is indeed the actual ramp mass - MTOM. That results in 3 **kg** of fuel. What you forgot is to convert the weight into a volume (note that the answers use litres). According to Wikipedia Avgas has a density of 0.72 kg/L, so the answer is: $$ \frac{1148 \, \text{kg} - 1145 \, \text{kg}}{0.72 \, \text{kg/L}} \approx 4.17 \, \text{L} \approx 4 \, \text{L} $$
stackexchange-aviation
{ "answer_score": 13, "question_score": 6, "tags": "fuel, performance calculation" }
Как научиться создавать программы на Java? Как научиться создавать программы на Java? Синтаксис я выучил. Но вызывает сложность создание программ. Пытаюсь делать по аналогии, компануя разные элементы. Для этого смотрю разные ролики на Youtube, где делают разные программы. Но далеко не всегда все сочетается между собой. Куча ошибок и пр. Думаю, может на основе проектов изучать? Подскажите сервисы для изучения Java на основе создания проектов Или с чего посоветуете начать?
На самом деле, если вы уже выучили синтаксис и базовые понятия, учиться можно на основе проектов на гитхабе. Найдите для начала небольшой проект, который вам понравится, и переписывайте код, начиная с входной точки. Важно понимать что делает каждая строчка, если что-то непонятно или будут вылезать ошибки - Гугл вам поможет. Если будете так делать, поймете как вообще пишутся программы, как стоит писать код, структуру проекта и т.д.
stackexchange-ru_stackoverflow
{ "answer_score": -1, "question_score": -2, "tags": "java" }
Redirect a product to other website I am looking for a way to have a product on my magento store, make it visible but not purchaseable and redirect users accessing it to another page/external url. Basically i have 6 products and would like to redirect all users who go to one of those products to another domain / external url. The product should be displayed but not be purchaseable - rather instead of add to cart link to an external url - or if possible even redirect the whole product detail page to another url... What’d be the best way to do that? i am trying for two days already but haven’t found the best solution yet… my programming skills aren't the best yet... thanks!
i think what you should do is to add one new attribute for redirect url , for your six products you can specify the redirect url in that attribute , and in the list.phtml you can place a condition that if a product has value in that attribute , you can use that value in anchor tag and in else case you cam use the regular product links for other products .
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "magento" }
How to effectively calculate $\int_0^\pi \sin^3x \sin(nx)dx$, $n\in \mathbb{N}$ How to effectively calculate $$\int_0^\pi \sin^3x \sin(nx)dx$$ I think by the formula: $$\sin 3x=3\sin x -4\sin^3x $$ So we get $$\sin^3x = \frac{3\sin x-\sin 3x}{4}$$ Plug in we obtain $$\frac{1}{4}\int_0^\pi (3\sin x-\sin 3x) \sin(nx)dx$$ Then how do I proceed?
Maybe it's a more advanced tool. I'm expose anyway my solution (for people who are interested). Remark that $x\mapsto \sin(x)\sin(nx)$ is even for all $n\in\mathbb N^*$, therefore, $$\int_0^{\pi}\sin^3(x)\sin(nx)\,\mathrm d x=\frac{1}{2}\int_{-\pi}^\pi\sin^3(x)\sin(nx)\,\mathrm d x.$$ As the OP remarked, $$\sin^3(x)=\frac{3}{4}\sin(x)-\frac{1}{4}\sin(3x).$$ Therefore, using Fourier series, we immediately obtain $$\int_{-\pi}^\pi\sin^3(x)\sin(nx)\,\mathrm d x=\begin{cases}\frac{3\pi}{4}&n=1\\\ -\frac{\pi}{4}&n=3\\\ 0&\text{otherwise}\end{cases}.$$
stackexchange-math
{ "answer_score": 2, "question_score": 5, "tags": "definite integrals, trigonometric integrals" }
Trigger to insert one record to new rows from another table I have a small app that inserts data into the database. I have a something like this `dbo.system.table1(col1, col2, col3)` and `table2(col1)` (`table2.col1` is just one single row). What I want to do is `insert the table2.col1 into table1.col3` when a new order is made. Also the `table2.col1` updates twice a day, so every time a new order is made with `table1` I need to keep the old `table1.col3` changes. I've tried CREATE TRIGGER dbo.TR_CHANGES ON dbo.SYSTEM AFTER INSERT AS UPDATE table1 SET table1.col3 = (SELECT col1 FROM table2 WHERE table1.col3 = table2.col1) But it ends updating col3 for all rows.
You need to include the `Inserted` pseudo table into your statement, to find the rows that were actually updated - and I would recommend using proper `JOIN` syntax instead of those nested subqueries - seems a lot easier to read and understand for me. So try this: CREATE TRIGGER dbo.TR_CHANGES ON dbo.SYSTEM AFTER INSERT AS UPDATE t1 SET col3 = t2.col1 FROM table1 t1 INNER JOIN table2 t2 ON t1.col3 = t2.col1 INNER JOIN inserted i ON t1.primarykeycol = i.primarykeycol You need to replace the `.primarykeycol` for the `Inserted` and `t1` tables with the **actual** primary key column for your table - this is needed to link the `Inserted` rows with the actual data table
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "sql, sql server, triggers" }
Block user account automatically if user doesn't verify his/her email within 24 hours of registration I am working on a project using **symfony** and I need to track, wether user has verified his/her email withing the 24 hours of creating a new account. How can I update the values in database automatically, so I can track this?
Create a php script which check the unverified members, and if the date is greater than 24 hours, remove him. Then just call your php script every hours or every days with a crontab. **See "What is a crontab?"** <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -2, "tags": "php, mysql, symfony, fosuserbundle" }
LINQPad throws System.OutOfMemoryException I've got this the simplest query ever in my LINQPad: var xml = XElement.Load(@"C:\\Users\\myth\sample.xml"); var query = from e in xml.Elements() select e; query.Dump(); The problem is that it gives me back System.OutOfMemoryException. XML file is around 120MB. I've read it here that LINQPad has a limitation of returning only 10000 rows. So, then I've tried putting it like this var query = (from e in xml.Elements() select e).Take(100); query.Dump(); yet it gave me back the same error. LINQPad version: v4.45.05
Figured it out by myself. When you are dealing with huge XML files (>100MB) or any other massive queries whatsoever, you need to have X64 Build installed.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "xml, out of memory, linqpad" }
How to create the google plus one button effect using jquery? When you look at the results on the google search page, you can see the google plus one button animation when you hover over the link or link description for every result. I was searching internet but was not able to find any tutorial how to achieve this effect on a image or element in general. Any suggestion or link to tutorial using jquery? Thanks in advance.
It is one image containing multiple frames. ~~I assume~~ The image is used as background via CSS and the background position is changed rapidly (through JavaScript) to create the animation effect. The image is: !+1 button
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 9, "tags": "javascript, jquery" }
Derivative result is $0 \over 0$. Does it imply the point isn't differentiable? $$f'(x) = {2x \over {4(x^2)^{3 \over 4}}}$$ for $x_0$ the derivative is $0 \over 0$, Which is defined as infinity as much as I know. Is it sufficient to say the above in order to prove $x_0=0$ isn't differentiable, or should I explain it in another way? Thanks
Two things: (1) Canonically, $\frac00$ has _no_ definition -- which is different from being defined as infinity. In fact, the classic definition of a derivative involves the limit of two things which go to $0$: just think of, for instance, taking the derivative of $f(t)=t^2$, where the result is $f'(x) = \lim\limits_{h\to0}\dfrac{(x+h)^2-x^2}{h}=\lim\limits_{h\to0}\dfrac{2xh+h^2}{h}$. Clearly this is a $\frac00$ limit, but that doesn't mean that the derivative is necessarily infinite. (2) You can simplify your expression substantially: rewrite the denominator as a direct power of $x$ using the rule $\left(a^b\right)^c=a^{bc}$, then rewrite the entire fraction as a single term in $x$ using the rule $\frac{a^b}{a^c}=a^{b-c}$. You should be able to clean up the constant terms in the process. Once you do this, you'll find that you no longer have a $\frac00$ limit and can evaluate it more directly.
stackexchange-math
{ "answer_score": 2, "question_score": 3, "tags": "calculus, real analysis, functions, derivatives" }
Grab text from HTML using PHP I have the following HTML on my web page. Is it possible to use PHP (or jQuery) to grab the content within the divs? I'd ultimately like to use it within a PHP script. <div id="selectedaddress"> <div>James</div> <div>Thomson</div> <div>London</div> <div>England</div> </div> Thank you.
use like this $('#selectedaddress').children().each(function(){ console.log($(this).text()); }); see console on jsfiddle - working example
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "javascript, php, jquery, html" }
How to set accumulated value using for in jQuery or JavaScript? The HTML code is like this: <ul class="gnb1depth"> <li></li> <li></li> <li></li> <li></li> </ul> $(document).ready(function () { var menu_count = $("ul.gnb1depth > li").size() for (var a = 0; a < menu_count; a++) { $("ul.gnb1depth > li").attr("test",a) }; }); The attribute of li that is set same value to 6(li count is 6). What can I do?
Use the setter version of .attr() which takes a function as the second argument $(document).ready(function () { $("ul.gnb1depth > li").attr('test', function (i) { return i }) }); In your case in each iteration of the loop, you are setting the attribute value of all `li` elements instead of targeting the `li` in the specified index.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, jquery, html, css" }
Using a BOOL Variable in a app Delegate : makes pointer from integer without a cast I`m doing something wrong with my app delegate, I'd appreciate if someone could have a look at this one . My **AppDelegate.h** : { BOOL *moveState; } @property (nonatomic) IBOutlet BOOL *moveState ; My **AppDelegate.m** : @synthesize moveState; and my ViewController from where I'm trying to set the moveState value : AppDelegate *moveUp = (AppDelegate *) [[UIApplication sharedApplication] delegate]; [moveUp setMoveState:YES]; It`s returning : _makes pointer from integer without a cast_
You declare a pointer to `BOOL` (`BOOL *moveState`) instead of a plain `BOOL` (`BOOL moveState`). Just change your interface: @interface Application : NSObject <UIApplicationDelegate> { BOOL moveState; } @property(nonatomic, assign) BOOL moveState; @end And by the way, you are probably designing the code wrong by storing the move state flag in the application delegate. Does the move state have anything to do with the application lifecycle? If not, why are you storing it in the application delegate? So that you can get it everywhere in the application through `[[UIApplication sharedApplication] delegate]`? That’s misusing the singleton pattern, take a good look at Miško Hevery’s article called Singletons are Pathological Liars and the articles linked from there.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "iphone, objective c" }
How to return objects in an NSArray at specified indexes? Example: I have an NSArray with 40 objects. What is the most efficient way to return ONLY those objects with index equal to a number specified in another NSArray (e.g {0, 27, 36} for example)? Can a predicate be used here? Or is there a more simple and efficient approach?
Why don't you just iterate over the index array and look up each index in the data array replacing the index with the looked-up object. In the end, the array that held the indices now holds the objects. If you don't want to wipe out your index array, then just create a new array of the same size as the index array and put the objects there. _You might be over-thinking the design of this and falling prey to micro-optimization. (Which is a bad thing.)_
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "objective c, nsarray" }
IntelliJ IDEA Bitbucket Git integration not pushing I initiated my git repo in my IntelliJ IDEA project. Then I click on share via Bitbucket under "Import into Version Control" Note: I've installed the plugin from jetbrains repository. All works fine, I even am able to create the repo on Bitbucket, but when I try to push, nothing happens. When I try again through VCS > GIT > Push, it says that there are no remotes defined. Please help. I mean, there's no error message nothing. I manage to push to github just fine though.
Following this answer, you might need to open the "Git Bash", and define a remote: git remote add origin http//IP/path/to/repository git push -u origin master > In IntelliJ IDEA right-click on project select Synchronize 'YourProject' For the reason behind the '`-u`' (upstream branch) option, see: "Why do I need to explicitly push a new branch?".
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 9, "tags": "git, intellij idea, bitbucket, phpstorm" }
Posting Answers instead of Questions While Q&A sites are certainly a good place to find answers to one's problems, I think it would be better to collect solutions. During my daily work I quite often solve a specific problem. Wouldn't it be nice if I could store the solution somewhere so that others can find it (including myself if I have the same problem later and forget how I solved it)? Kind of a Code Snippet Repository. I think the quality of the solutions would be much better this way. You could also formulate questions and attach them to the solution (= answer), so it would look and behave like a Q&A site. The process of posting a solution would have to be very easy, of course. Nobody wants to spend too much time after solving a problem. I imagine that there has to be a tight integration with the OS or IDE, maybe directly allow posting of marked code with a shortcut. What do you think?
Yes, you can post a question and answer it yourself. But it would be polite to wait at least a day before accepting the answer to allow others to provide an even better answer.
stackexchange-meta
{ "answer_score": 1, "question_score": 1, "tags": "discussion, questions, answers, posting" }
Can factory methods return multiple instances? It is a factory method if it returns an instance of a class but is it a factory method if it returns multiple (an array of) instances?
If you need it to return multiple instances, then do it, regardless of how it is called. I would say it is indeed a factory method, but this doesn't matter that much. Perhaps you can have a factory method for returning a single instance, and then another one that calls the first one multiple times.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 5, "tags": "design patterns, language agnostic, factory pattern" }
z-index problem with helper clone This is my code (please see < $('.first').draggable({ cancel: null, helper: 'clone' }); $('.second').droppable({ over: function(event, ui) { $(this).css('z-index', 1); ui.helper.css('z-index', 0); } }); I am trying to have the helper clone go _under_ the droppable element when it is dragged over it. What am I doing wrong?
When you drag the `.first` element, the generated draggable element is positioned absolutely _and_ added after the `.second` element. An absolutely positioned element gets a higher precedence. To fix this, use `ui.helper.css('z-index', "-1");` instead of `ui.helper.css('z-index', 0);`.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "jquery" }
Kill process by name and user I am trying to figure out if there is a way to kill all processes by name and user. E.g. I want to kill all the Java instances run by user myuser. As of the moment I do: $ pgrep -u myuser java 2185 3281 3413 3504 22534 26174 27554 which gives a list of the pid of java run by mysuer. Then I kill each pid individually. Is there a better way to do this? Thanks in advance!
Use `killall(1)`: killall -u myuser java Note that you may need to do this via `sudo`, and you may need `-9` to kill processes that swallow `SIGTERM`: sudo killall -9 -u myuser java
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 6, "tags": "process, kill" }
Copying backup table into similar table with new columns Copying data from a backup table into a production table is as easy as... INSERT INTO TBL_A SELECT * FROM TBL_A_BK However, if I add a new column to TBL_A after making my backup, I now have to specify every column in the INSERT statement and the SELECT statement. The more columns in my table, the more frustrating this is, seems like there should be an easier way?
No, there is no easier way. The correct method is to write: INSERT INTO TBL_A (col1, col2, ... colX) SELECT colA, colB, ... colZ FROM TBL_B Any other method is fragile -- it's not at all obvious what should happen when one table has more columns than the other, or the columns are in a different order. That said, you can easily write code in some application language that builds an ordered column list for each table from metadata and creates the SQL on the fly for you. In addition, some languages (I"m thinking of an obscure one called R:Base, there are likely others) have other statements (in R:Base it's APPEND) that INSERT by matching column names, leaving others NULL.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "sql" }
Alcohol in checked-in baggage in transit through Saudi Arabia with Saudi Airlines I am looking for cheap tickets from Germany to India via Saudi Arabia with Saudi Airlines. While I am not interested in carrying or having alcohol or any sort on board, I would like to know if it is permitted to carry it via checked-in baggage. Is that fine to do so, or is it prohibited as well? I could only find information with respect to alcohol for cabin baggage. I will be in transit at Riyadh and will not leave the airport. Googling shows people have different opinions but most of them are hunches or assumptions. Does anyone here have first-hand experience?
In addition to the **_"better safe than sorry"_** case, I finally found a link which makes it explicitly clear: < > Prohibited (also for transit passengers): alcoholic beverages, firearms or other lethal weapons; drugs of narcotic nature (except medicines for personal use and if holding prescription); pork products; natural pearls. Hope this helps others!
stackexchange-travel
{ "answer_score": 16, "question_score": 13, "tags": "transit, luggage, alcohol, saudi arabia, saudi airlines" }
context free grammar problem $L$ is the context free grammar over $\\{a, b\\}$ $S \rightarrow aSb \; | \;bR \; |\;Ra$ $R \rightarrow bR \;|\;aR\;|\;\epsilon$ Briefly describe this CFG with English sentences and prove your description. Then give a CFG for the complement of $L$. $\\\$ I think the CFG is a language with equal amount of $a$ at the beginning and $b$ in the end, in the middle with a string that consists of $a$ and $b$, and either starts with $b$ or ends with $a$. But I'm not sure if it's correct nor do I know how to formally prove my description. For the complement, I'm not sure how to design the CFG. Is anyone able to solve this problem? Thanks.
Let $A = \\{a,b\\}$. Then the language $L$ is the least solution in $S$ of the system of equations \begin{align} S &= aSb + bR + Ra \\\ R &= bR + aR + 1 \end{align} where $+$ denotes union and $1$ denotes the empty word. The second equation gives $R = (a+b)R + 1 = AR + 1$ and has $R = A^*$ as unique solution. Reporting in the first equation yields $S = aSb + bA^* + A^*a$. Setting $K = bA^* + A^*a$, it can be written as $S = aSb + K$, which leads the solution $$ L = \\{ a^nub^n \mid n \geqslant 0 \text{ and } u \in K \\} $$ For the second part, I have nothing to add to the excellent suggestion of Arthur Fischer.
stackexchange-math
{ "answer_score": 2, "question_score": 4, "tags": "computer science, computability, automata, context free grammar" }
Lighting the menora in shul and at home. How many brochos need be said? Our shul has a minyan for mincha before sunset and for maariv after sunset. Between the two, the chanuka lights are kindled. There is a later maariv minyan; the chanuka lights are again kindled before this maariv. This gives rise to the following questions (which could not be posed to the Rav last night – the first night - as he was away): 1) I lit the lights in shul after mincha and went home to light there. Should I have said the brocho “shehecheyonu” at home after saying it in shul? (I light one menora for me and my wife.) Related question. 2) When the second minyan for maariv assembled, should the one lighting the lights have made the brochos (a) if he had already lit at home and (b) if he had not lit at home? Could you say that the blessings had already been made on this menora and are not needed again?
Shaarei Teshuva 671:11 says: If you are the lighter in shul by mincha, you say all brachos in shul. When you go home, you will not say shehecheyanu unless you are saying it for others. If you lit at home and said all of the brachos, you still say all of the brachos when lighting in shul later, including shehecheyanu. I think the reasoning is that each new minyan is a new obligation, even if everyone in the minyan already lit individually. I tried looking up the zera emes, but couldn't find a teshuva on chanuka. I am unfamiliar with the roshei teivos for the sefer that quotes him. In a cleaner copy of my Shulchan Aruch it looks like mem-ches-beis. Anyone?
stackexchange-judaism
{ "answer_score": 3, "question_score": 5, "tags": "halacha, blessing, chanuka, lighting" }
Convert first row of pandas dataframe to column name I have a pandas dataframe 0 1 2 0 pass fail warning 1 50 12 34 I am trying to convert first row as column name something like this pass fail warning 0 50 12 34 I am currently doing this by renaming the column name newdf.rename(columns={0: 'pass', 1: 'fail', 2:'warning'}) and then deleting the first row. Any better way to do it .
I believe need to add parameter to `read_html`: df = pd.read_html(url, header=1)[0] Or: df = pd.read_html(url, skiprows=1)[0]
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 14, "tags": "python, pandas" }
Truncate a float and a double in java I want to truncate a float and a double value in java. Following are my requirements: 1\. if i have 12.49688f, it should be printed as 12.49 without rounding off 2\. if it is 12.456 in double, it should be printed as 12.45 without rounding off 3\. In any case if the value is like 12.0, it should be printed as 12 only. condition 3 is to be always kept in mind.It should be concurrent with truncating logic.
try this out- DecimalFormat df = new DecimalFormat("##.##"); df.setRoundingMode(RoundingMode.DOWN); System.out.println(df.format(12.49688f)); System.out.println(df.format(12.456)); System.out.println(df.format(12.0)); Here, we are using decimal formatter for formating. The roundmode is set to DOWN, so that it will not auto-round the decimal place. The expected result is: 12.49 12.45 12
stackexchange-stackoverflow
{ "answer_score": 27, "question_score": 14, "tags": "java, floating point, double, truncate" }
update from external storage I am trying to update system to either Android 5.0 lillipop or Android 4.4 KitKat. I formated sd card to FAT32, and moved rom there. When in recovery I used `apply update from external storage ` ` failed to verify whole-file signature` `signature verification failed` I downloaded both roms from here the same thing happened for second rom. I am using Onetouch EVO7. if this may help recovery says `recovery system v4.00` Also I can not use fastboot to connect with device (waiting for device), so I am using adb instead. Device is rooted using kingo root
The 'ROMS' you have downloaded are actually just the Google Apps that would come with a stock ROM. > Every new Android Smartphone comes with various pre-installed apps such as Gmail, Google Play Store, Google Chrome, etc., which are referred as Google proprietary apps or specifically Gapps. These apps are developed under Google Licensing terms in order to prevent usage in any other mobile operating system and modification by the third-party developers. This is the reason that you can’t get your hands-on any of the Gapps after installing Custom ROMs. The site you linked to is providing these apps in a way that allows you to easily add them to a custom ROM you already have on your device. It is not providing the custom ROM. You will need to look elsewhere for this as they are specific to each device model.
stackexchange-android
{ "answer_score": 1, "question_score": -2, "tags": "rom update" }
How to refetch fullCalendar(jQuery plugin) from colorbox iframe? My question is how to refetch events to fullCalendar from an iframe? The calendar is on the main page, and the user can edit the calender trough a colorbox popup (iframe). When the user saves the changes i want the calender to reload the events trough the json file. i have tried: `$('#kalender1', window.parent.document).fullCalendar('refetchEvents');` And its not working. /Linus _**SOLVED_** I solved it.. It has to be: `parent.$('#SELECTOR').fullCalendar('refetchEvents')` instead of `$('#SELECTOR', window.parent.document).fullCalendar('refetchEvents');`
I solved it.. It has to be: `parent.$('#SELECTOR').fullCalendar('refetchEvents')` instead of `$('#SELECTOR', window.parent.document).fullCalendar('refetchEvents');`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "jquery, json, iframe, fullcalendar, colorbox" }
New "type" of node? Not sure how to phrase this question but basically I'm creating an non-profit's internal portal within Drupal. They deal with school sponsorship of children and we want to manage this database in Drupal. Within administration the staff should be able to add/edit/delete a Child from sponsorship much in the same way you would deal with a content node. I don't want to add Content Type 'Child' as it's not directly for the front-facing website. But would prefer to create a "new node type" (does this make sense?)....in the same way that the Commerce module allows for addition of Products, separate from content. How would I go about this? (I think I'm missing a key technical word for "Node type"...)
I think the technical term you're looking for is 'entity type'. A node is an 'entity' in Drupal, as is a User, Taxonomy Term, Commerce Product etc. The simplest way to create a new entity type is with the Entity Construction Kit: > The Entity Construction Kit builds upon the entity system to create a flexible and extensible data modeling system both with a UI for site builders, and with useful abstractions (classes, plugins, etc) to help developers use entities with ease. But you can of course do it manually too. The Examples module contains a fully working module that defines a custom entity type, if you wanted to code your own solution that would be the best place to start.
stackexchange-drupal
{ "answer_score": 8, "question_score": 5, "tags": "7, nodes" }
Display message or block when View Page is null or empty I have a `Content Type : Events` and i have created 3 events they are currently `published` and displayed in `Page` ie `Display as View`. If there are no published `Events` then it should display a custom message as "No Events" or a "block". I am trying to work on views with null values but i could not get it. Is there any thing like this.
On your configuration Views in the right you've "Advanced" zone, if you click on it you will see more options and "No results behavior" that will let you do what you want when the view doesn't return results. !enter image description here
stackexchange-drupal
{ "answer_score": 1, "question_score": 0, "tags": "7, views, blocks" }
Assigning values to unmapped property Suppose, I have a Customer class with some properties like * name, * id, * object of CompetentAuthority class etc. name,id etc is mapped in .hbm file but i have taken icollection of CompetentAuthority object and I didnt do any entery in .hbm file for CompetentAuthority(one-to-many). In CompetentAuthority class i have taken Customer object and in .hbm file of CompetentAuthority i did many-to-one relationship. Nnow,i want list of customers with it's CompetentAuthority list but as its just an object and no mapping is done,criteria API doesn't allow me to do innerjoin;it gives me error like "cannot resolve property" Is there any way to achieve this.
If you are wanting to use the Criteria API to apply an INNER JOIN, then no you cannot do that. The CompetentAuthority object needs to be mapped with NHibernate and the Customer object's mapping file will need to be modified to establish the relationship between the two entities. If for some reason you are not able to map the CompetentAuthority, you could take advantage of mixing the ISession.CreateSQLQuery() method and the Transformers.AliasToBean() method which will allow you to hydrate an unmapped entity. For more information on this technique, please refer to the Official NHibernate documentation section titled "Returning non-managed entities" or search around for using the AliasToBean() method: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "asp.net mvc 3, nhibernate" }
USD Coin Balance Check By Web3 Now I am getting trouble on checking the USDC balance in my wallet address using web3. USDC is also said that it is ERC20 token, but when I checked the token contract 0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 This doesn't contain the erc20 standard. So I guess I can't use the traditional token balance checking way in this coin. Also I tried in traditional way, but it never work. How can I check the USDC balance / and create transfer transaction from one address to another using Web3?
This is proxy contract, which means that it delegates actual work to another contract, probably to this one: 0x0882477e7895bdc5cea7cb1552ed914ab157fe56, which in turn is ERC-20 compliant. Proxy contract allows its administrator to change address of the contract actual work is delegated to, effectively changing smart contract logic. Proxy contracts like this one are implemented via `DELEGATECALL` opcode that executes code of another contract on behalf of this contract, i.e. called code has access to the storage and balance of calling contract.
stackexchange-ethereum
{ "answer_score": 5, "question_score": 5, "tags": "web3js, erc 20, ethereum wallet dapp, nodejs" }
How to know who is(are) the currently logged in user(s) How to know who is(are) the currently logged in user(s) in a spring MVC web application so that we can present the jsp views accordingly
Use below code to get logged in User details. Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { Object principal = auth.getPrincipal(); if (principal instanceof User) { return ((User) principal); } } And in JSP page you can get logged in user details like below. ${pageContext['request'].userPrincipal.principal.id}
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "spring mvc" }
Optimization of parallelepiped inside an ellipsoid Let $K \in R^3$ the ellipsoid given by the equation $ \frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2} = 1 $ with $a,b,c > 0$ , let $(x,y,z) \in K$ on the first octant, consider the parallelepiped of vertices $(\pm x,\pm y,\pm z)$ inscribed on $K$ with volume $V = 8xyz$. How can I find the maximum possible value of $V$? I stuck with this hard problem for me i tried to find the explicit equation and then get the maximum values : Let $P=(x,y,z)$ be a point on the ellipsoid with $x,y,z\gt 0$.Then i took the eight different points with $P_i (\pm x,\pm y,\pm z)$ the vertices of a parallelepiped with the side length $2x , 2y$ and $2z$. Then, the volume parallelepiped is $V = 2x\cdot 2y\cdot 2z = 8 xyz$ and i remembered that **$V$ is maximum if and only if $V^2$ is maximum** . Some help please.
Because $$\frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2} = 1$$ We have $$\left(\frac{x^2}{a^2}\frac{y^2}{b^2}\frac{z^2}{c^2}\right)^{1/3} \le \frac{1}{3}\left(\frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2}\right) = \frac{1}{3}$$ Thus $$V=8|xyz| \le \frac{8abc}{\sqrt{27}}$$
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "multivariable calculus, derivatives, optimization, volume" }
Changing the initial file location of NodeJS app on Azure I have a NodeJS app on Azure which was written in Javascript. The `app.js` was in the root directory and was detected automatically when deploying to Azure via Git. I recently converted the app to Typescript with a build directory, so the root file is now in `dist/app.js`. When debugging in VS Code, I can easily change `launch.json` to point to the new location, however now when pushing changes to Azure it no longer works. How do I specifiy the launch file for Azure?
You can modify the `web.config` in your root directory of your application. Modify the `<handlers>` tag: <handlers> <!-- Indicates that the app.js file is a node.js site to be handled by the iisnode module --> <add name="iisnode" path="/dist/app.js" verb="*" modules="iisnode"/> </handlers> Modify the rewirte mod : <rule name="DynamicContent"> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/> </conditions> <action type="Rewrite" url="dist\app.js"/> </rule>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, node.js, git, azure, typescript" }
Rails/iPhone: recommended place of doing OAuth I'm building a (Rails-based) web service with a mobile app (iPhone) as frontend. In order to allow people to login using Facebook, I've built something using devise and omniauth that allows the user to log in using Facebook and store the credentials in the database. This works perfectly, all from the web app. However, now the second part: I want to let users log in via the mobile app. Of course, there are the FB Connect libraries, but they give the mobile app access to the Graph API. Instead, I would like a mobile log-in screen that authorizes Rails to access the data. This is because later on, users might use both the iPhone app and web app. What would be the recommended way of doing this? Are there any best practices?
I solved it by doing the authorization using FB Connect and the FB app. After authorizing, the FB app opens my app again, and I can read out the access token. Which I can then send to the server and use there.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "iphone, ruby on rails, facebook, oauth" }
What library should be included to use TransparentBlt? What library should be included to use TransparentBlt? This is VC98 (Visual Studio 6) linking to the Gdi32.lib. (Other GDI functions such as BitBlt link as expected), and the compilers compiles with out error or warning. Even though the Gdi32.lib is included, yet the linker returns this error: mtcombo.obj : error LNK2001: unresolved external symbol __imp__TransparentBlt@44 C:\Work\Montel\Targ2_12\guitest.exe : fatal error LNK1120: 1 unresolved externals What am I missing?
AFAIK, you will need the Msimg32.lib <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c, winapi, linker, gdi, visual studio 6" }
Where can I find the android.R.* files? I am looking for the preset android files that come with the Android os. Can someone direct me to the source?
(Android install path)\android-sdk-windows\platforms\android-version\data\res Hope this is what you mean.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "android, listview, android layout, android manifest, android xml" }
Return a unique row based on a single column I have a table (Employee). **Employee** ID Name Salary Department ------------------------------ 1 Steve 10000 SQ 2 Buck 15000 AS 3 Dan 10000 SQ 4 Dave 10000 AS 5 Jack 30000 AS 6 Amy 8000 GM I need to return one employee per each department. For instance, for the above date I need to return the data as below: ID Name Salary Department ------------------------------ 1 Steve 10000 SQ ( I can either return Steve or Dan for this group SQ) 2 Buck 15000 AS ( I can either return Buck or Dave or Jack for this group AS) 6 Amy 8000 GM
This is a good use for `row_number()`: select id, name, salary, department from (select t.*, row_number() over (partition by department order by department) as seqnum from t ) t where seqnum = 1 If you want the first or last id, use `order by id asc` or `order by id desc` in the `row_number()` partitioning clause. If you want a random row, use `order by dbms_random.value`.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "sql, oracle" }
Adding two divs either side of text in a list item I have a function which receives a list item. When it does, I want to add two divs to either side of the text in the list item: FOr example, when it receives the item: <li class="sortedli"> Call Type </li> it should become: <li class="sortedli"> <div class="sel-display-on">&nbsp;</div> Call Type <div class="sel-trash-on">&nbsp;</div> </li> However, my function receive: function (event, ui) { $(this).prepend("<div class=\"sel-display-on\"></div>"); $(this).append("<div class=\"sel-trash-on\"></div>"); } Produces this markup: <div class="sel-display-on"></div> <li class="sortedli" style="">Caller Id</li> <div class="sel-trash-on"></div> How may I rectify this?
You're appending/prepending to `.sortedli`'s parent. Use context to find the right element: receive: function (event, ui) { $('.sortedli', this).prepend("<div class=\"sel-display-on\"></div>"); $('.sortedli', this).append("<div class=\"sel-trash-on\"></div>"); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, jquery ui" }
Remove \u from string? I have a few words in a list that are of the type `'\uword'`. I want to replace the `'\u'` with an empty string. I looked around on SO but nothing has worked for me so far. I tried converting to a raw string using `"%r"%word` but that didn't work. I also tried using `word.encode('unicode-escape')` but haven't gotten anywhere. Any ideas? **EDIT** Adding code word = '\u2019' word.encode('unicode-escape') print(word) # error word = '\u2019' word = "%r"%word print(word) # error
I was making an error in assuming that the `.encode` method of strings modifies the string inplace similar to the `.sort()` method of a list. But according to the documentation > The opposite method of bytes.decode() is str.encode(), which returns a bytes representation of the Unicode string, encoded in the requested encoding. def remove_u(word): word_u = (word.encode('unicode-escape')).decode("utf-8", "strict") if r'\u' in word_u: # print(True) return word_u.split('\\u')[1] return word vocabulary_ = [remove_u(each_word) for each_word in vocabulary_]
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "python, regex, python unicode, unicode escapes" }
'ProtocolError('Connection aborted.', InvalidURL("URL can't contain control characters. ' ' (found at least ' ')"))': /simple/pandas While trying to install any package using pip I am getting error: for example pip install pandas --proxy proxy_value WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', InvalidURL("URL can't contain control characters. ' ' (found at least ' ')"))': /simple/pandas I have uninstalled python and freshly installed python 3.9.13 and set the system variables to C:\Users\richa1\AppData\Local\Programs\Python\Python39\Scripts\ I have checked with 3.10.5 too. But still not able to fix it. I am not sure if this is some issue with installed file or something I need to set.
As discussed in the comments, the error stems from a malformed HTTP proxy setting. In this case, the `http_proxy` variable had been set to `''` instead of the empty string, and a quote character is indeed a control character not allowed in an URL.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "python, pip" }
Why does Google use the IP address of local DNS servers to locate me? Assuming that Google can figure out where a machine (with its given IP address) is roughly located, why doesn't Google use the IP address of a machine versus using the IP address of a local DNS server to determine the machine's location? Any thoughts on this?
Short answer - Load Balancing is done (partly) based on a DNS lookup. The DNS lookup happens before you request the web page, and is done by the local DNS server - so Google needs to use that. Long version: When your machine makes a DNS lookup it enquires against the local DNS server. Thus when working out the IP address to provide [ unless you are directly querying Googles nameservers ], it only has the address of the DNS server, so it has to use that to approximate your location - because the DNS server does not forward your details on with the request (and indeed, if someone else recently made a similar enquiry against that nameserver it may not even ask Google - prefering to return its cached answer.
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "dns, ip, geolocation" }
How to plot the function expanded in a series Suppose some function f[x,y]. I want to expand it in series, like g[x_,y_] = Series[f[x,y], {y,0,2}] After that I need to plot the graphic of $g$. But it is impossible because of `O[y^2]` term in the expression for g. How to throw out this `O[y^2]` term?
For this purpose use `Normal`, f[x_, y_] = Exp[x*y] g[x_, y_] = Normal@Series[f[x, y], {y, 0, 2}] > 1 + x y + (x^2 y^2)/2 Plot3D[g[x, y], {x, 0, 2}, {y, 0, 2}]
stackexchange-mathematica
{ "answer_score": 4, "question_score": 1, "tags": "series expansion" }
Gradle/Java Defining version in a single place Sorry for the simplistic question, but I'm new to both Java and Gradle. I'm just looking for the simplest solution to do this. So I created a class like: public final class VERSION { public static final Integer majorVersion = 1; public static final Integer minorVersion = 0; public static final Integer patchVersion = 0; ... } While I'm new to Java, I've employed patterns similar to this with a variety of languages, and I'm happy with it. The issue is that my project's build.gradle file also defines: version "1.0.0-SNAPSHOT" What's a simple way where I can define the version numbers in one place, so I stop forgetting to update them in sync?
The simple way is to define it in the build file or in the gradle.properties file. Have a version.properties file in your project resources (src/main/resources); version=@version@ , and configure the `processResources` task to filter this file in order to replace the version key(s) in this file: def tokens = ['version': project.version] processResources { filesMatching('version.properties') { filter(ReplaceTokens, tokens: tokens) } inputs.properties(tokens); } Then, in your Java code, simply load the version from the `version.properties` resource: Properties props = new Properties(); props.load(MyClass.class.getResourceAsStream("/version.properties"); String version = props.getProperty("version"); Not tested, but you should get the idea.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, gradle" }
Achieving better DB performance I have a website backed by a relational database comprised of the usual e-commerce related tables (Order, OrderItem, ShoppingCart, CreditCard, Payment, Customer, Address, etc...). The stored proc. which returns order history is painfully slow due to the amount of data + the numerous joins which must occur, and depending on the search parameters it sometimes times out (despite the indexing that is in place). The DB schema is pretty well normalized and I believe I can achieve better performance by moving toward something like a data warehouse. DW projects aren't trivial and then there's the issue of keeping the data in sync so I was wondering if anyone knows of a shortcut. Perhaps an out-of the box solution that will create the DW schema and keep the data in sync (via triggers perhaps). I've heard of Lucene but it seems geared more toward text searches and document management. Does anyone have other suggestions?
Materialized Views are what you might use in Oracle. They give you the "keeping the data in sync" feature you are looking for combined with fast access of aggregate data. Since you didn't mention any specifics (platform, server specs, number of rows, number of hits/second, etc) of your platform, I can't really help much more than that. Of course, we are assuming you've already checked that all your SQL is written properly and optimally, that your indexing is correct, that you are properly using caching in all levels of your app, that your DB server has enough RAM, fast hard drives, etc. Also, have you considered denormalizing your schema, just enough to serve up your most common queries faster? that's better than implementing an entire data warehouse, which might not even be what you want anyway. Usually a data warehouse is for reporting purposes, not for serving interactive apps.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "data warehouse, database" }
How do I display/update a tweet from a designated hashtag every 30 seconds I have a php webpage where the user selects a Twitter hashtag. Using the Twitter API I'd like to then display the most current tweet for that hashtag and update this every 30 seconds. Any support on this would be great. Thanks
I would use the search API, a sample url, content encoded with `json`: Replace **TAG** with your Tag, **%23** = #. **rpp=1** means return only one tweet (results_per_page). Now with `json_decode();` and a bit of code you can output the newest Tweet. For the refresh use Javascript or redirect the page to itself every 30 second..
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, api, twitter, hashtag" }
logging out user with logout button will not redirect keeps going to php file instead of index so im trying to log my user out and return them to the home screen but im just getting redirected to my logout.php file (white screen) any help here is the code: (logout.php file) <?php session_Start(); unset($_SESSION['user_id']); header("location../index.php"); ?> Button: <li class="nav-item"> <?php if(isset($_SESSION['user_id'])): ?> <a href="logout.php" class="nav-link btn-success logout-btn">Logout</a> <?php endif; ?> </li> tried a bunch of different things and nothings working i expect to be redirected to the index.php login screen
Because the location header is malformed, so the browser won't follow it. Try: header("Location: ../index.php");
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, html" }
Radio button selected after submit a form I have a form where i used radio buttom and when radio buttom is selected and submit the buttom the value is pass but radio buttom not selected. My code for the radio buttom in the form is written bellow. echo '<form name="posts_form" id="post_form" method="post" action="">'; echo $displaycategory = get_option('posts_displaycategory'); echo '<p>Display Date:<br><input type="radio" value="YES"'; echo $posts_displaydate . '" name="posts_displaydate" id="posts_displaydate" /> YES</p>'; echo '<input type="radio" value="NO"'; echo $posts_displaydate . '" name="posts_displaydate" id="posts_displaydate" /> NO</p>'; Now i want to select the radio buttom when i select the radio buttom.Thank you
you need to check the condition with $posts_displaydate like below or write down the full code so i will write. if($posts_displaydate=='YES') echo "checked"; if($posts_displaydate=='NO') echo "checked";
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "wordpress, radio button" }
Shortcomings of modelling roles as boolean columns on User table I'm working on a Rails app using CanCan for RBAC and I only have 3 roles and _maybe_ I'll add 1 or 2 more somewhere down the track. In the past I've always had roles as their own entity, joined to users via a m2m link-table. With so few, and static, roles, that seems like overkill. So I'm thinking of simply adding boolean columns to my Users table for each role. I could also use a bitmask (like the CanCan example does) but I'm not too keen on storing multiple values in a single column. So my question is, what's the best thing to do in this situation: bitmasks, multiple boolean columns, or a properly normalized m2m relationship?
Operating on the principle of YAGNI would drive my decision to use the separate bit columns for each role. Even if you add a couple more columns over time it's still easier to manage than a m2m link-table. I completely agree with not using bitmasks as they obscure the meaning of the data. I'm only addressing this from the SQL side as I have no experience with Rails, CanCan or RBAC.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, ruby on rails, cancan, rbac" }
Slice list with numpy array I have a list, lets say: list = ['A1', 'A2', 'A3'] I have some data, that returns with an Numpy array of either: array([0]) array([1]) array([2]) Which are indicating the index of the corresponding list index. But how can I get the array to print the list indication? What I would like at the end result: array_result = array([1]) print(f'Result : {array_result[list]}') Result : A2 So basically slice a list with an array list
Try simple boolean indexing on both the arrays - import numpy as np l = ['A1', 'A2', 'A3'] #recommend not using 'list' as variable name array_result = np.array([0]) l[array_result[0]] 'A1'
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, arrays, list, numpy, slice" }
Extract x{} from some text using REGEX I need to clean some portion text like: 1. "P{ MARGIN: 0px } Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression." 2. "BODY{ MARGIN: 0px } Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression." do you have some regex for me? Thanks in advance. Note: For .Net desktop application using System.Text.RegularExpressions. Thanks in advance.
Your requirements are pretty vague, but this pattern, \w+\s*{.*?} Will match one or more of word characters followed by an open bracket, followed by any number of whitespace characters, followed by any number of characters (non-greedily), followed by a close bracket. For example: string input = "P { MARGIN: 0px } Lorem Ipsum"; string output = Regex.Match(input, @"\w+\s*{.*?}").Value; System.Console.WriteLine(output); // P { MARGIN: 0px }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": ".net, regex" }
$1^2$+$2^2$-$2×3^2$+$4^2$+$5^2$-$2×6^2$+$...$+$9997^2$+$9998^2$-$2×9999^2$ ∵ For any positive integer $n$ $n^2-2(n+1)^2+(n+2)^2$ = $n^2-2n^2-4n-2+n^2+4n+4=2$ ∵ $1^2$+$2^2$-$2×3^2$+$4^2$+$5^2$-$2×6^2$+$...$+$9997^2$+$9998^2$-$2×9999^2$ = $1^2+(2^2-2×3^2+4^2)+(5^2-2×6^2+7^2)+...+(9995^2-2×9996^2+9997^2)+9998^2-2×9999^2$ = $1+(2+2+...+2)+9998^2-2×9999^2$ I do not know how many lots of two will be inside the aforementioned parenthesis.
There would be $((9995-2)/3)+1$ lots of 2. Following; $1+2×(((9995-2)/3)+1)+9998^2-2×9999^2$ $2×3332+(9998^2-9999^2)+(1-9999^2)$ $6664+(9998-9999)(9998+9999)+(1-9999)(1+9999)$ $6664-19997-99980000$ = $-99993333$
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "summation" }
When can you start wishing people a good weekend? In Belgian culture (and some others, I suppose) it is not uncommon to wish people a good weekend when you meet them on Friday. Not just when you go home after work, but also in the store around noon, or even in the morning. Is this common in English too? If you send a business e-mail on Friday, is it weird to end it with "have a good weekend"?
In an email, such "premature" weekend well-wishing would be fine. In fact, you might say that it sort of sends an implicit message, something along the lines of: (a) I'm not sure if we'll communicate again before the end of the business day, or (b) I realize you may not read this message until this afternoon. In other words, I might be _less_ likely to close a Friday morning email that way with my secretary or boss (who I normally see every couple hours through the course of the day), and _more_ likely to do so in an email to that IT assistant who works on the other side of building (who I may not talk with again until Monday or Tuesday next week). But no, nothing “weird” about it – not in the U.S., either.
stackexchange-english
{ "answer_score": 7, "question_score": 4, "tags": "business language, greetings" }
How to pass immutable data through two webpages that can't be user-generated I have a flash application (a game) and it needs to pass data to a php page to save the user, and the user's score. However I don't want the user to be able to alter the score him/herself or to initial a scoring without using the application. What is the best way to do this?
If the client (i.e. flash) is keeping track of/generating the score, there is no secure way for you to send the score to the server. Whatever the swf file can do, an attacker can also imitate. The only secure way is to send each user move or action to the server. The server is responsible for the state of the game and maintaining the score; the client just generates the moves. With such an approach, an attacker cannot manipulate the score. He can still bypass your SWF file, but to get a high score he still has to make the right moves. The attacker can make a bot to make the moves intelligently; to avoid that you can only use security by obscurity.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, flash, security" }
Is every algebraic curve birational to a planar curve Let $X$ be an algebraic curve over an algebraically closed field $k$. Does there exist a polynomial $f\in k[x,y]$ such that $X$ is birational to the curve $\\{f(x,y)=0\\}$? I think I can prove this using Noether Normalization Lemma. Is this correct? If yes, is it too much? That is, is there an easier argument?
Two curves are birational if and only if their function fields are isomorphic. $k(X)$ has transcendence degree $1$, so pick a transcendental element $x \in X$. Then $k(X)$ is a finite extension of $k(x)$. By the primitive element theorem (in this context a birational version of Noether normalization), there exists a primitive element $y \in k(X)$ such that $k(X) = k(x)[y]$; $y$ satisfies a minimal polynomial $f(x, y) = 0$ over $k[x]$, and the conclusion follows. **Edit:** Above I implicitly assumed that the extension $k(x) \to k(X)$ is separable. This is automatic if $k$ has characteristic $0$. If $k$ has characteristic $p$ we need to choose $x$ more carefully and I am not sure how to do this without going through the characteristic-$p$ proof of Noether normalization.
stackexchange-math
{ "answer_score": 20, "question_score": 13, "tags": "algebraic geometry, riemann surfaces, algebraic curves" }
Integral of $\int \sin^2 x \cos^2 x dx$ This seems pretty simple to me but I can't get it. $$\int \sin^2 x \cos^2 x dx$$ $$\int (1-\cos^2 x) \cos^2 x dx$$ I know there is a rule in my book (with little explanation) that tells me when I had an odd and an even degree on two trig functions I should split the odd and convert it to an identity but this way seems easier, and I can't get an answer either way. $$\int \cos^3 dx - \int \cos^ 5 x dx$$ I am not sure where to go from here, I don't know how to get the integral of $\cos^3 x$
Write integrand as $(\sin x \cos x)^2 = (\frac{1}{2}\sin 2x)^2 $. Then use the following facts: * $\sin^2 2x = 1-\cos^2 2x$ * $\cos^2 2x = \frac{1}{2}(\cos 4x +1)$ _Note: The original question asked for the integral of_ $\sin^2 x \cos^2 x.$
stackexchange-math
{ "answer_score": 5, "question_score": 0, "tags": "calculus, integration" }
How to simulate sets of random variables from skewed distribution with given correlation I’d like to simulate sets of correlated random variates $X_1, X_2, \dots, X_N$ given an $N \times N$ correlation matrix, where each of the $X$'s comes from the same positively skewed distribution. What’s a technique for doing this? As an example, how would I simulate pairs ($X_1, X_2$) where $X$ follows a lognormal distribution and cor($X_1, X_2$) = 0.7?
Gaussian copula. Let $F$ be your favorite distribution function, log-normal or whatever. Let $\Psi$ be the target correlation matrix. Construct a Gaussian copula $Z(\Sigma) \in \mathbb{R}^n$ as follows. 1. Draw $W \sim \mathcal{N}(0,I_n)$ 2. Let $X = \Sigma^{1/2}W$ 3. Let $Z(\Sigma) = [\Phi(X_1)\quad \ldots \quad \Phi(X_n)]$ where $\Phi$ is standard normal CDF. Now, let's use your favorite distribution to obtain $$Y(\Sigma) = [F^{-1}(Z(\Sigma)_1) \ldots F^{-1}(Z(\Sigma)_n)]$$ Calculate the correlation of $Y(\Sigma)$ (you need to draw many $Y(\Sigma)$'s to do this..) Repeat the entire exercise until you find $\Sigma$ such that $Corr(Y(\Sigma))=\Psi$. When searching for appropriate $\Sigma$, use the fact that each non-diagonal element of $\Sigma$ has one-to-one monotone relation to the corresponding element of $Corr(Y(\Sigma))$.
stackexchange-stats
{ "answer_score": 1, "question_score": 2, "tags": "probability, correlation, simulation" }
Kotlin getter / setter when using a primary constructor The example is from a Kotlin-course I'm doing: class Car { var speed: Int = 0 get() = field set(value) { field = value } } If I like to use a primary constructor like this: class Car(var speed: Int) **How would I have to write the getter / setter in that case?**
You cannot write getters/setters inside of the constructor, you can do the following: 1. Create variable inside class whose value taken from constructor. class Car(speed: Int) { var speed = speed get() = field set(value) { field = value } } 2. Use `@JvmField` annotation to restrict compiler not to auto-generate getters/setters and implement one yourself class Car(@JvmField private var speed: Int) { fun getSpeed() = speed fun setSpeed(value: Int) { speed = value } }
stackexchange-stackoverflow
{ "answer_score": 39, "question_score": 21, "tags": "kotlin" }
Storing dynamic values from input fields in a JS object, and converting to JSON 1. How can I add two values from two HTML `<input>` fields to a JS object? 2. How can I then convert that object into JSON? Code: $("input").each(function() { var jsonObj=[]; var id = $(#box1).val(); var email = $(#box2).val(); item = {}; item ["title"] = id; item ["email"] = email; jsonObj.push(item); });
Your code (with the selectors put in quotes) will successfully store an object with the properties `title` and `email` in the array...briefly. Then the array will be eligible for garbage collection because you don't keep a reference to it anywhere outside the function. If your goal is to keep track of the information longer than one iteration of the `each` loop, declare and initialize your array _outside_ of the function: var arr=[]; $("input").each(function() { var id = $("#box1").val(); var email = $("#box2").val(); item = {}; item ["title"] = id; item ["email"] = email; arr.push(item); }); But I can't immediately see a reason you'd do that repeatedly while looping through the `input` elements on the page.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "javascript, jquery, json" }
How to compare current time to a time range formated as a string using Javascript I have two times formatted as strings in my database, they are in the format 8:30AM and 9:00 PM respectively. Using Javascript, I wan't to get the current time and see if I am within the rang of the two times. How would I go about doing this
Convert the start, end and current time into JavaScript Date objects, then check if `start <= current < end`. It gets tricky if the start date becomes less than end date: // The un-important bits var d0 = new Date("01/01/2001 " + "8:30 AM"); var d1 = new Date("01/01/2001 " + "9:00 PM"); var d = new Date("01/01/2001"); d.setHours(new Date().getHours()); d.setMinutes(new Date().getMinutes()); // For testing console.log(d0, d, d1); // The important bit console.log( d0 < d1 ? (d0 <= d && d < d1) : (d1 <= d && d < d0) == false );
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "javascript, date, time, compare" }
Pointer to an array of pointers in Pascal I don't know how to access the content of an array of pointers by a pointer. Here's an example: Type PInteger = ^Integer; IntegerArrayP = array of PInteger; PIntegerArrayP = ^IntegerArray; var variable: Integer; parrp: PIntegerArrayP; arrp: IntegerArrayP; begin SetLength(arrp, 5); parrp := @arrp; For variable := Low(arrp) to High(arrp) do begin arrp[variable] := New(PInteger); (parrp^)[variable]^ := variable; WriteLn('parrp: ', arrp[variable]^); end; end. In my opinion it should be done like this `(ptabp^)[variable]^ := variable;` But I guess I'm wrong.
You are right. Parens might be omitted. What pascal compiler do you use? Proper usage of `New` routine: New(arrp[variable]) ; parrp^[variable]^ := variable; P.S. Do you really need these pointer types here? P.P.S. Now I see an error: PIntegerArrayP = ^IntegerArray **P** ;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "pointers, pascal, dynamic variables" }
How do I wire this inline rotary lamp dimmer I bought this to add dimming abilities to my table lamp... But after opening it up am not too sure where to solder the wires. ![]( ![](
Looking at the rear view picture: top left terminal is one side; extreme right terminal is the other side. This is assuming that the pot has a switch that turns OFF when the pot is at one extreme or the other (usually full Left). Be aware that the triac appears to be tiny and will handle only a few watts of power.
stackexchange-electronics
{ "answer_score": -1, "question_score": -1, "tags": "voltage, voltage regulator, power electronics, dimmer" }
The elements in a finite field. I am reading some lecture notes from MIT Open Courseware. One of the theorems states that the elements in a finite field of order $q$ are the $q$ distinct roots of the polynomial $x^q - x$. I can see that the nonzero roots of this polynomial would form a cyclic group under multiplication. I do not understand how these elements would _add_ to form a group. I think that one interpretation of the elements in a finite field $F_{p^n}$ is to let them be polynomials with coefficients in $F_p$ and the operations are modular polynomial arithmetic with modulus any irreducible polynomial in $F_p[x]$ with degree $n$.
The statement you are referring to is a _description_ of the finite field with $q$ elements, not a _construction_. If $q$ is a prime power, you can define a field $F$ with $q$ elements by various methods, and whichever construction you choose, you will have the identity $x^q-x=\prod_{a\in F}(x-a)$ in the polynomial ring $F[x]$, which means that all elements of $F$ are simple roots of the polynomial $x^p-x$ (which happens to have its coefficients in the prime subfield of $F$). This description is not enough however to tell those roots apart, or to tell how they are added and multiplied in$~F$. That is part of the construction of $F$ which you have to do beforehand. From this description it is not even clear that different constructions of a field with $q$ elements will all result in isomorphic fields, although that happens to be true. But given two constructions there may not be any canonical way to choose an isomorphism between the two resulting fields (unless $q$ is a prime number).
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "finite fields" }
Swift string to NSDate I am trying to convert a string to an NSDate. I found how to do it on a couple posts, but for some reason doesn't work. let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss" var test = dictionary["time"] as! String loadedItem.time = dateFormatter.dateFromString(test) println("Time recorded as: \(loadedItem.time)") println("Time from server: " + test) The console log is: Time recorded as: nil Time from server: 2015-07-07 21:46:11 Time recorded as: nil Time from server: 2015-07-07 21:58:09 Time recorded as: nil Time from server: 2015-07-07 22:02:35 Time recorded as: nil Time from server: 2015-07-07 23:46:49 As you can see, the string is never formatted.
HH is 24 hour format let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" var test = dictionary["time"] as! String loadedItem.time = dateFormatter.dateFromString(test) println("Time recorded as: \(loadedItem.time)") println("Time from server: " + test) So, just edit date format hh to HH. dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" hope it helps
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "swift, nsdate" }
Correct usage of vector<int>::size_type I saw in some very well known books on C++ that -- vector<int> ivec; for (vector<int>::size_type i = 0; i != 10; ++i) { ivec.push_back(i); ivec.push_back(i); // duplicate copies of each number } I was wondering why `vector<int>::size_type` is used here. They are not comparing `i` with size of the vector. Intent is to insert 10 `int`'s in the vector, so `int i = 0` would be a right thing to do, isn't it ? `vector<int>::size_type` would be `typedef` for `std::size_t` which in turn will be `unsinged int`, but here we are storing `int`'s in the `vector`. Please clarify my understanding about `vector<int>::size_type`. Is it fair to use it in the for loop above ?
Basically, the above code is 'fine' in the sense that it compiles and does the intended job, as others have said. When they said the intent was to insert ten `int`s in the vector, the `int`s are guaranteed positive because of how the loop is formatted, so the `unsigned int` will just convert into `int`. However, I don't believe this is good practice as you said - the size type has nothing to do with the type of the elements being inserted - the size type is basically always an `unsigned int`. Just using `int` or `value_type` would obviously make the intent of the code clearer.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "c++, c++11" }
CSS with AngularJs custom validation I'm having trouble getting a message to display when the field input is invalid. I can see the classes being correctly applied to the element i.e. ng-dirty ng-invalid ng-invalid-pattern so I just need to make the error message display. Is there an issue with my html? Thanks! <form ng-controller="FormCtrl" name="TestForm" action=" method="post" novalidate> <div class="form-group"> <input class="form-control" type="text" id="vld" name="vld" data-ng-pattern="/(^$)|(\b\d{9}\b)/" data-ng-model="model.tfn"> <span class="error" data-ng-show="model.tfn.$invalid">Correct input etc...</span> </div> </form>
The information you are looking for is part of the FormController. You need to setup a formController via ng-form directive: <div class="form-group" ng-form="myForm"> <input class="form-control" type="text" id="vld" name="vld" data-ng-pattern="/(^$)|(\b\d{9}\b)/" data-mg-model="model.tfn"> <span class="error" data-ng-show="myForm.vld.$invalid">Correct input etc...</span> </div> If this is done you may access the information by [Name of the OFrmController].[Name of the input field].$invalid e.g. myForm.vld.$invalid
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "angularjs" }
Token sale and one-time address On many token sale site I see workflow when user suggested to send ETH to one time address and it is changed each time I refreshing page. I am trying to understand how it implemented? Only way I see is to have main contract that acts as factory that can create children contracts per request that only has fallback function that forwards incoming ETH, `msg.sender` and `msg.value` to the main one. But this approach looks insecure - each subcontract creation takes gas and I potentially can exhaust main contract only by refreshing site's page and asking each time for new pay-in address. Could you explain how it works?
It is likely that this unnamed token sale doesn't use smart contracts at all. For more information see this answer: * ICO crowdsale without smart contract
stackexchange-ethereum
{ "answer_score": 1, "question_score": 1, "tags": "contract design, tokens" }
Save a part of GoogleMap for accessing offline I found similar question, but not exactly what I want. I want to allow user draw for example a rectangle on the map and when I know coordinates can I save this piece of map for further accessing it when user is using maps in offline mode? Does anyone know how to do that or if it is possible at all? Thanks for every good advice.
I did a lot of research on that subject and I am sure that google maps aren't really designed for offline browsing, unless you cache selected part of the map in google maps app. As you cannot currently save maps outside of GM app, then it is sure that you can't do more advanced things such as saving maps in custom shapes. Maybe they'll implement these features in the future..
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "android, google maps, google maps api 2, saving data" }
Issue in finding power of a number using user defined functions MY CODE along with the output The following code is not working. It has no errors, am doing some mistake in the logic I think. I want to find power of a number using functions. How to make this code work? The code: #include<iostream> using namespace std; int pow(int); int main() { int x,p,ans; cout<<"Enter a number"; cin>>x; cout<<"Enter the power of the number"; cin>>p; ans=pow(x); cout<<ans; return 0; } int pow(int) { int a=1,i,p,x; for(i=0;i<=p;i++) { a=a*x; } return a; }
Here is working code: #include<iostream> using namespace std; int pow(int, int); int main() { int x,p,ans; cout<<"Enter a number"; cin>>x; cout<<"Enter the power of the number"; cin>>p; ans=pow(x, p); cout<<ans; return 0; } int pow(int x, int p) { int a=1,i; for(i=0;i<=p;i++) { a=a*x; } return a; } Ideone You have to pass the local variables into the function instead of defining new ones with the same name. What you are doing should give you warnings about unused variables (`x` and `p` in `main`) and it also invokes undefined behavior in `pow` because of ininitialized reads of the variables defined there. Also your function was wrong. You were just multiplying 1 with a value a bunch of times, which stays 1 forever.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -5, "tags": "c++" }
Display local language for OSM data in TileMill I'm following the instructions here to create a minimalist style map for Japan: < Now, I've downloaded the OSM data, used _osm2pgsql_ , created the tilemill project and it now properly displays in TileMill. However, all the displayed city name labels are in the Romanized (english) characters. Is there a way that I can get the Japanese (Kanji, hiragana, etc) displayed in place of thier romainzed dipictions? ( _Street names do appear in the original Japanese, sometimes with Romanized letters in parens_ ) I'm assuming that the original Japanese names are contained in the osm.pbf, but somewhere along the pipeline they are being ignored. Any ideas?
You have to expand the default.style of osm2pgsql to import the local name as well. The file is a simple text file, which you can edit with any text editor. You will find a line node,way name text linear inside. This will import only the international readable name. For local names, add node,way name:ja text linear in a separate line. You have to go through the tilemill style as well, look for the part where `name` or `name:en` is used, and replace it with something like if exist `name:ja` then use `name:ja` else use `name`. **EDIT** Make sure TileMill is using your postgis database, and not the shapefiles that are in the `layers` folder. Those files do not have names with Japanese characters.
stackexchange-gis
{ "answer_score": 2, "question_score": 1, "tags": "openstreetmap, labeling, tilemill" }
Blackberry and Iphone Video format transcoding from WMV I need to be able to deploy a video to both Iphone and Blackberry platform, Is there a shared format that they both can play? The deployment is via email as attachment. This can save me some time with testing, if someone had the same problem and can offer input i would help me a bunch and I would like some input about the trans-coding process, my client doesn't care if he needs to pay a license free to use a component. If someone wrote code that converts to this joint format using an external library of command line tool, I would be happy to learn which tool or library you used. I am converting from WMV. Thank you very much.
I've been able to get .mp4 (h264 encoded) video working on iOS, Android, and BlackBerry. It's the closest thing to a mobile standard as far as I'm aware. Sending videos to people via e-mail is a pretty bad delivery method, though.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "iphone, blackberry, video, wmv, transcoding" }
Flipped over dataTable primefaces Is it possible to flip datatable in primefaces, in order to have headers in the left not in the top? I have following table: <p:dataTable value="#{rolesMgmt.listOfMapsRoles}" var="map" id = "dataTable"> <p:columns value="#{rolesMgmt.columns}" var="column"> <f:facet name="header"> <h:outputText value="#{column.header}" /> </f:facet> <h:outputText value="#{map[column.property]}" /> </p:columns> </p:dataTable> ![enter image description here]( As you see, I have a lot of headers and 2-3 rows and I need to flip this table
No this is not possible by using some attribute on the `p:dataTable` itself. For this to be achieved you need to transpose your model. Maybe you can achieve something by manipulating the responsiveness. But if you have lots of columns AND lots of rows, maybe you should think of just displaying a 'summary' in a datatable and have a details view. Or use a `p:datagrid` (showcase) where you can sort of free-format your records or a plain ui:repeat? Since you do not seem to need sorting/filtering etc in this case. The `p:datatable` seems overkill to me now
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "jsf, primefaces, datatable" }
answer phone call & display button iphone I'm new to iphone developing. I want create a app just like following way. When phone call is coming to the phone & user answer it. then display the button. after the call end button is disappear. is there any way to do it. help me thanks
iOS doesn't allow access to most telephony functions, so you can't do things like display a button when a user answers a call.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "iphone, button, user interface" }
Wasteland horror series in trade paperback DC published an anthology horror series in the '90s called _Wasteland_. I have never seen a collected edition of this series. My question is: has the entire series, or any part of it, ever been collected in trade paperback?
All signs point to " **No.** " Searching just brings up people lamenting the fact that there is no collected edition. This interview with creator, John Ostrander is from 2012, and states: > It’s worth mentioning that Wasteland has never been collected and may very well remain out of print. I’m not sure if the world of comics would be any more inviting to such a series today than it was back in 1987, but don’t let public taste deprive you of these great comics. Every page is worth seeking out and with minimal effort, you’ll discover that I’m not wrong. I can't find anything more recent that contradicts that statement.
stackexchange-scifi
{ "answer_score": 2, "question_score": 1, "tags": "dc, horror" }
Why does the pandas the dataframe column order change automatically? When I were output the result to CSV file, I generated a pandas dataframe. But the dataframe column order changed automatically, I am curious Why would this happened? **Problem Image :** ![enter image description here](
As Youn Elan pointed out, python dictionaries aren't ordered, so if you use a dictionary to provide your data, the columns will end up randomly ordered. You can use the `columns` argument to set the order of the columns explicitly though: import pandas as pd before = pd.DataFrame({'lake_id': range(3), 'area': (['a', 'b', 'c'])}) print 'before' print before after = pd.DataFrame({'lake_id': range(3), 'area': (['a', 'b', 'c'])}, columns=['lake_id', 'area']) print 'after' print after Result: before area lake_id 0 a 0 1 b 1 2 c 2 after lake_id area 0 0 a 1 1 b 2 2 c
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "python, pandas, dataframe" }
Agrupar vértices em função de weights Com base num df de ligações pretendo selecionar todos os caminhos possíveis constituídos apenas por vértices cujas ligações verifiquem uma determinada condição neste caso valor >=3 library(igraph) library(dplyr) df <- data.frame( origem = c("A", "A", "A", "B", "C", "F", "D", "C"), destino = c("B", "C", "D", "E", "F", "G", "H", "G"), valor = c(3, 4, 2, 1, 5, 2, 7, 6)) df <- df %>% filter ( valor >= 3) O objetivo é agrupar todos os vértices que estão incluídos em caminhos com valor >=3 registando numa data.frame o ID do grupo e para cada ID a identificação dos vértices que o constituem (um vértice não estará presente em mais de um grupo). No caso apresentado teria 2 grupos constituídos da seguinte forma: ID X 1 A 1 B 1 C 1 F 1 G 2 D 2 H
Usando _igraph_ , pode gerar um grafo a partir de um `subset` e usar `clusters` para verificar os grupos formados: grafo <- graph_from_data_frame(subset(df, valor >= 3), directed = FALSE) # Ou, se já está com os dados completos como igraph: grafo.f <- graph_from_data_frame(df, directed = FALSE) grafo <- subgraph.edges(grafo.f, E(grafo.f)[valor >= 3]) clusters(grafo)$membership #> A C D B F H G #> 1 1 2 1 1 2 1 plot(cluster_label_prop(grafo), grafo, edge.label = E(grafo)$valor) ![inserir a descrição da imagem aqui]( Se precisa do resultado como _data.frame_ : grupos <- clusters(grafo)$membership resultado <- data.frame(ID = names(grupos), X = grupos) # ou, se estiver usando tidyverse: resultado <- tibble::enframe(grupos)
stackexchange-pt_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "r, grafo" }
Continuously Insert Data to Database through asmx Web Service I have a web service (hosted on IIS) that insert data to database(Xampp) [WebMethod] public void Insert(int a) { string query = "INSERT INTO result (A) VALUES('" + a + "')"; if (this.OpenConnection()) { MySqlCommand cmd = new MySqlCommand(query, connection); cmd.ExecuteNonQuery(); this.CloseConnection(); } } The first time I consume this web service it works charm, but for the second time when it tries consume this service again, it returns an error message **"The operation has timed out"** on my coding s1.Insert(a); The Web service works correctly again when I restart my web service in IIS, but it is not going to work as it has to work continuously. Any hopes?
The problem I can see could be your this object that remains for second call but it could not open connection. Make object of your class instead of using this. e.g [WebMethod] public void Insert(int a) { string query = "INSERT INTO result (A) VALUES('" + a + "')"; YourClass obj = new YourClass(); //Open connection here if (obj.OpenConnection()) { MySqlCommand cmd = new MySqlCommand(query, connection); cmd.ExecuteNonQuery(); this.CloseConnection(); } else throw new Exception("Problem in opening connection"); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, sql, web services, iis, asmx" }
Upgrading SSD Capacity - Clone Drive I currently have a 60GB SSD that I have as my OS drive for Windows 7 partition and Fedora17 partition. Most data is stored on my 500GB hard disk. I have upgraded to a 120GB drive, and want to clone the 60GB drive over to my 120 drive. Right now my current layout is roughly 40GB for Windows 7 and 20 for Linux (GRUB - Windows -Linux). What I am trying to figure out is if I were to clone that directly to the 120GB I would be left with something like (GRUB - 40GB Windows - 20 Linux - 60 Spare). My Linux install is pretty simple, and won't need too much more space, most of the space I would like to dedicate to Windows. Is having my extra space at the end (after my Linux partition) a problem? Or does it not matter? Or would I be better to remove my Linux partition, clone the existing data to the new drive, and set up my Linux partition on the last 20 GB or so of the 120 drive?
I tried several different clone utilities and none seemed to work well. At first I had to reinstall Grub2 using `grub2-install /dev/sdXY` which worked to boot Linux but my Windows 7 installation had errors saying something similar to cannot find /H/S/C on hdX. I tried using EaseUS Partition Manager and Acronis. Neither worked. Eventually I tried Clone Disk, which I don't remember the differences between the different software listed above and Clone Disk, but one starts the clone at a given sector, and the other at a given block. (I think). Anyways, Clone Disk worked great. No problems, didn't even have to reinstall grub2.
stackexchange-unix
{ "answer_score": 0, "question_score": 3, "tags": "dual boot, ssd" }
php - how to sort an array with values like "+1", "-20" I have a PHP script with an array like this: array ( "+15" => 5, "-5" => 20, "+2" => 2, "-1" => 9 ) The keys are all unique (the +15 etc). I want to sort by the keys so this: foreach($array as $k => $v ) { echo $k . ' has a count of ' . $v; } any ideas on sorting by the keys with + and -'s. I can't get that working correctly
Would natsort() work? From php.net: <? $array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png"); asort($array1); echo "Standard sorting\n"; print_r($array1); natsort($array2); echo "\nNatural order sorting\n"; print_r($array2); ?> Output: Standard sorting Array ( [3] => img1.png [1] => img10.png [0] => img12.png [2] => img2.png ) Natural order sorting Array ( [3] => img1.png [2] => img2.png [1] => img10.png [0] => img12.png )
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, arrays, sorting" }
How to wait for a tag not to contain attribute using protractor I have an element which has attribute disabled='disabled'. How can i wait, until element stop having that attribute at all, not to be changed on 'enabled', but just not having that attribute at all anymore. I am checking on attribute value like this: el.getAttribute('disabled').then(function (atr) { expect(atr).toMatch('disabled'); }); Now i need to wait for a condition, when this attribute disappear, but didn't find any suitable solution.
You can use the expected condition `elementToBeClickable`. It will wait for the element to be displayed and not disabled: var EC = ExpectedConditions; browser.wait(EC.elementToBeClickable(element), 5000);
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "jasmine, protractor" }
The inverse in the sense of MOORE-PENROSAE $AA^{-1}B=B$ On which conditions we have $$AA^{-1}B=B$$ A, B are nonnegative definite symmetric $n\times n-$matrices, and $A^{-1}$ is the Moore-Penrose inverse of A.
Let me write $A^+$ for the Moore-Penrose inverse. Then $AA^+$ is the orthogonal projector onto the range of $A$. Therefore $AA^+B=B$ iff the range of $B$ is contained in the range of $A$.
stackexchange-math
{ "answer_score": 1, "question_score": -1, "tags": "matrices, matrix calculus, matrix rank" }
Open a new form using button in C# Hi i'm doing a simple activity in c# . i want to open a new form2 using a button and the form1 will automatically close when i press that button .Here's My code: Form2 form2 = new Form2(); form2.ShowDialog(); this.Close(); Now i don't have idea What method will i use to close automatically the form1. Thank you..
Instead of using `this.Close();` use `this.Hide()` and on formclosing event of `Form2` give `form1.Show()`. for more information go through this link (I asked this question before).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c#, android activity" }
How to change border colour in dropdown in fluent ui? `<Dropdown/>` has styles props. which expects `IDropdownStyles`.But not able to change border outline colour. I tried this, root: { width: 300, color: "red", backgroundColor: "red", borderColor: "red", borderTopColor: "red", outlineColor: "red", borderRightColor: "red", }, dropdown: { width: 300, color: "red", backgroundColor: "red", borderColor: "blue", borderTopColor: "red" , outlineColor: "red", borderRightColor: "red", }, But the colour is not reflected. Is any other way to achieve this?
Use `title` property inside `styles`: <Dropdown ... styles={{ title: { borderColor: 'red', } }} /> Codepen working example.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "fluent ui, fluentui react" }