INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Should I see evidence of neutron induced gammas on a background spectrum? If I am looking at a background gamma spectrum taken from a neutron spallation source whilst the beam was off (IE in a shutdown period), should I expect to see emissions coming from neutron induced reactions? I have a peak at 834keV which I can't really attribute to anything other than a 72Ge(n,n') reaction. I am using a Germanium detector, but should I really be seeing evidence of (n,n') reactions on a background spectrum?
I would note that Mn54 has a 300 day half life, and also emits at 834keV - you are likely seeing activation of material from the past neutron activity (Mn is a fairly standard alloying addition in steels and aluminum alloys).
stackexchange-physics
{ "answer_score": 3, "question_score": 1, "tags": "nuclear physics, spectroscopy, data analysis, gamma rays" }
DELETE FROM table WHERE condition in other table is met I am new to SQL so I appreciate your help and ask your forgiveness if this is something simple, I couldn't find the answer that helped me in other related posts. I have to tables `PRC_FIX` and `IM_ITEM`. They both have a column `ITEM_NO`. I would like to delete a line in `PRC_FIX` where `IM_ITEM.ITEM_VEND_NO` equals `TOYM`. Do I need to do some sort of join? Thanks again for your help. Edit: I do not need help setting up the cascading DELETE. I am asking how to DELETE a line from ONLY `PRC_FIX` when a matching line in `IM_ITEM` meet a specific condition.
Clever approach : DELETE PRC_FIX FROM PRC_FIX INNER JOIN IM_ITEM ON IM_ITEM.ITEM_NO = PRC_FIX.ITEM_NO AND IM_ITEM.ITEM_VEND_NO = 'TOYM' I hope to be helpful for you :)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql, sql" }
Testing two elements with the same text I have a page with two element containing the "some text", but cannot confirm it in my test. Simplest example is this: <div>some text</div> <div>some text</div> const selector = 'div' const text = 'some text' cy.get(selector) .contains(text) .should('have.length', 2); **Cypress log** > expected to have a length of 2 but got 1
Unfortunately `.contains()` only ever returns one element. If multiple are found, the first one is returned. You can instead add `:contains()` into the selector. Since the selector and text are variables, a string template can build the final selector. cy.get(`${selector}:contains(${text})`) .should('have.length', 2); or put it in a `.filter()` cy.get(selector) .filter(`:contains(${text})`) .should('have.length', 2);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "cypress" }
Ensure that a variable is only set once I need to ensure that an article is only sold once. This must be ensured over several threads as well. Is it enough to check if the `buyer` variable is not null? So in my opinion, the second caller will receive an `AlreadyBoughtException`? public synchronized void buy(Buyer buyer) throws AlreadyBoughtException { if (this.buyer != null) { throw new AlreadyBoughtException(); } System.out.println(buyer + " bought article " + identifier); this.buyer = buyer; this.sold = true; } Is this thread-safe and can I assume that there is no chance that the article cannot be bought when the `buy` method is called at the same time (exactly the same time)?
The fact that your method is synchronized does make it safe - so long as this is the only way you ever update the buyer.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, exception, thread safety" }
In a cylic group of order $12$, we can find an element $g \in G$ such that $x^2 = g $ has no solutions. > $$ \textbf{PROBLEM} $$ > > If $G = \\{ g^n : 0 \leq n \leq 11 \\} $. Then we can find an element $a \in G$ such that the equation $x^2 = a$ has no solutions. $$ \textbf{ATTEMPT} $$ My claim is that the multiples of $3$ would do. So, take $a = g^3$. We claim that $x^2 = g^3$ has no solutions. Suppose $b \in G$ is a solution. $b$ must be of the form $g^k$ for some $0 \leq k \leq 11 $. Therefore, we have $$ (g^k)^2 = g^3 \implies g^{2k} = g^3 \implies g^{2k - 3} = e \implies |g| \; \; \text{divides} \; \; 2k - 3$$ In other words, $|g|n_0 = 2k - 3 $ for some $n_0 \in \mathbb{Z}$. But I dont see how I can get a contradiction from here. Any suggestion will greatly be appreaciated. thanks
Your group is isomorphic to the additive group $\mathbb{Z}/12\mathbb{Z}$. Thus, transposing to an additive notation, your problem is to solve the equation $x + x = a$ in this group. It should be clear now that your equation has no solution for $a = 1$.
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "abstract algebra, group theory" }
Power of a Point 2 Let $B$, $C$, and $D$ be points on a circle. Let $\overline{BC}$ and the tangent to the circle at $D$ intersect at $A$. If $AB = 4$, $AD = 8$, and $\overline{AC} \perp \overline{AD}$, then find $CD$. ![Diagram]( * * * This looks like a Power of a Point problem but I don't know how to apply it. All solutions are greatly appreciated.
Well, you have $$AC.AB = AD^2$$, then $AC = \frac{8^2}{4} = 16$. Now, you can easily compute $CD$: $CD^2 = AD^2 + AC^2 = 8^2 + 16^2 = 320$, then $CD = 8\sqrt{5}$.
stackexchange-math
{ "answer_score": 2, "question_score": -2, "tags": "geometry, circles" }
Link domain to specific Apache port I need to link a specific domain to a port in an Apache server. I'm looking for something like this: www.test.com links to 127.0.0.1:80 www.sub.test.com links to 127.0.0.1:90 I already created two VirtualHosts in my httpd conf: <VirtualHost *:80> ServerName www.test.com DocumentRoot /var/www/html/test </VirtualHost> <VirtualHost *:90> ServerName www.sub.test.com DocumentRoot /var/www/html/sub-test </VirtualHost> But when I try to access `www.sub.test.com` I got `port 80` website. Can someone help me?
While you can assign the domains to ports, the default port for http is 80, so any address you specify without an explicit port will use port 80. As for why you get the other website, as you don't specify a port, the browser uses port 80, and that is the only defined host for that port. The first defined `VirtualHost` is special as it will be selected of no entry matches. Why are you using different ports? Just use port 80 for both names, and Apache will do what you probably want.
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "apache http server, centos, webserver, centos 6" }
The right way to save spinner to sharepreferences I have a spinner that have 3 values populated from array-list. I want to save the spinner selected value to shared preferences so it can be loaded back again when the use comes back to the app. What is the correct way to do this (to avoid future problems) 1- Save position of the selection 2- Save the text of the selection 3- Get the position/text of the selection, get the corresponding enum, and save the enum name. I am leaning towards the 3rd option incase the positions/texts changed in later updates but I am wondering what is the correct way of doing such task Thank you
Save position (1 variant) and text (2 variant) are bad practice. Because text for your spinner items may will change in the future and their position can be changed. I think, that you need to create enum or `@TypeDef` element and save it to sharedPreferences. `@TypeDef` is more performance but enum is more functionality (if you use Kotlin you can use `sealed` classes). For this solution just write mapper that can map enum to spinner item. If you use enum, the best way is to save it name `ENUM.name()`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "android" }
Two unknowns in Arithmetic Progression I have a problem in my maths book which says > Find the arithmetic sequence in which $T_8 = 11$ and $T_{10}$ is the additive inverse of $T_{17}$ I don't have a first term of common difference to solve it, so I managed to make two equations to find the first term and common difference from them. Here they are. first equation $a + 7d = 11$ second equation since $T_{10} + T_{17} = 0$ therefore $a+9d + a+16d = 0 ~~\Rightarrow~~ 2a + 25d = 0$ So what I did is subtracting the first equation from the second one to form this equation with two unknowns $a – 18d = 11$ This is what I came up with and I can't solve the equations, any help?
To solve linear equations with n variables, you need a minimum of n equations. Here, we have 2 variables and 2 equations, so it can be solved. There are many methods to solve the equations. But the most common method is elimination method. In this method, you multiply an equation with a constant, such that the coefficient of the equation becomes equal to the coefficient of the other equation. Then you subtract them, and you are left with one variable. You have the equations: $$ a + 7d = 11 $$ $$ 2a + 25d = 0 $$ Now multiply the first equation by 2, you get: $$2a+14d=22$$ Subtract this with the second equation. You get: $$ 2a+14d - 2a - 25d = 22$$ $$ - 11d = 22 $$ This gives $d= -2 $. Putting this value in first equation, we get: $$a = 11 - 7.(-2) = 25 $$ So we have, $a=25, d=-2$
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "arithmetic, arithmetic progressions" }
What are the hidden Shortcuts in Swing Components? I found out `Ctrl`+`Shift`+`O` in my JTextPane changes the ComponentOrientation. For my own TextEditor I have to disable this, but are there other Shortcuts in JTextPane or in other Swing-Components? Keyboard bindings `Ctrl`-`X`, `Ctrl`-`C`, and `Ctrl`-`V` are known. Are there more?
> but are there other Shortcuts in JTextPane or in other Swing-Components? See Key Bindings which lists all the bindings and shows how to disable a binding you don't want.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "java, swing, keyboard shortcuts, hidden, shortcut" }
Filter only three characters in shell I am trying to parse a command in shell, and in one of the options I want to save in a variable if a string has `"r"`, `"w"`, `"x"`, one of those, all of them, or a mix, but only these three. No other characters should be allowed! I tried a case where: $2 in *r*) ;; *w*) ;; *x*) ;; * ) echo no ;; esac But in this case if there is written `zr` it will pass, as it has an `"r"`. I only want to make it pass as long as it has one of these three, the three of them, or two of them (any kind of combination), but no other characters.
In BASH you can use regex for this check like this: re='^[rwx]+$' s='rw' [[ $s =~ $re ]] && echo "yes" || echo "no" yes s='zr' [[ $s =~ $re ]] && echo "yes" || echo "no" no Regex `^[rwx]+$` will allow 1 or more of `r` or `w` or `x` letters.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "bash, shell, parsing, command" }
Como pegar 2 arrays PHP e juntar em 1 string Tenho 2 arrays em PHP que vem de um formulário `$_POST['qtd']` e `$_POST['ing']`: array(2) { [0]=> string(1) "1" [1]=> string(1) "2" } array(2) { [0]=> string(1) "a" [1]=> string(1) "b" } Tem como, de alguma forma, juntar eles em uma variável que fosse assim? $variavel = "(1,'a'), (2,'b')"; Com isso vou fazer um `INSERT` na tabela de MYSQL que deverá ficar assim: INSERT INTO tabela (qtd, ing) VALUES (1,'a'), (2,'b');
Pode usar `array_map()` para pegar os repectivos valores de cada array (par a par) e dentro da função anônima montar o formato e/ou sanitizar a string. Como o retorno da função é um novo array, use a função `implode()` para separar todos os elementos por vírigula na string gerada: $arr1 = array(1,2,3); $arr2 = array('a', 'b', 'c'); $valores = array_map(function($a, $b){ return sprintf("('%s', '%s')", $a, $b);}, $arr1, $arr2); echo implode(',', $valores); Saída: ('1', 'a'),('2', 'b'),('3', 'c')
stackexchange-pt_stackoverflow
{ "answer_score": 5, "question_score": 5, "tags": "php, array" }
Explode MySQL string in Column I have a MySQL Database and want to search a specific column for specific data. {"pump":"0","track":"0","bats":"1","acc":"1","batl":"6","gpslev":"5"} This is the info in the column I would like to extract bats when it is 0 and then display it on my PHP screen using PHP strings and echo. I have read about `SUBSTRING_INDEX` but when I use it it displays everything to the left of bats. I need a search string that can search on bats and `WHERE bats=0` Any assistance will be appreciated.
Use the JSON functions: SELECT col->"$.bats" -- and maybe other columns you want here FROM yourTable WHERE col->"$.bats" = '0'; ## Demo **Edit:** If your version of MySQL does not support JSON functions, we can still try using `REGEXP`: SELECT * FROM yourTable WHERE col REGEXP '"bats":"0"';
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, mysql" }
TextOut() and the Cambria Math font The Cambria Math font has UNICODE characters beyond `0xFFFF`. You can see them in a Word document, just by inserting a Symbol and selecting the Cambria Math font. By the way, the Windows Character Map does not show these characters. My question is : how to exhibit those UNICODE characters in a Windows app using `TextOut()` ?
To display these supplementary code points you need to use UTF-16 surrogate pairs. A surrogate pair is a way of representing single code points beyond `0xFFFF` as two wide characters. You simply pass a surrogate pair to `TextOut()` and it will be displayed.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "windows, winapi" }
How to find documents by startsWith() in Futon I am working with `CouchDB` and I have to find documents whose name start with "5463" The document structure I have is : > {_id: "018bdd61897af56d0b3c421d4dfb1a92", _rev: "1-b37c710c91450b93510f547194631aa0", type: "active_matter", id: 177, name: "3009/TR02", ismaster: true} So in `Futon` I am trying something like : function(doc) { if (doc.ismaster == true && (doc.name).startsWith("5463")){ emit([doc.type], doc); } } but not results are getted. What I am doing wrong?
It seems like CouchDB doesn't support the `startsWith` method. Instead use `indexOf`, with a little conditional you can use it the same way. Using your Example: function(doc){ if(doc.ismaster && (doc.name.indexOf('5463') == 0)){ emit([doc.type], doc); } } That will work the same way as `startsWith`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "javascript, couchdb, couchdb futon" }
EyeFi doesn't support CF cards. Are there any alternatives that do? Pretty much as what the title asks. Any ideas anyone? Is there any particular, technical limitation for using this technology with CF cards?
Here is the latest answer on CF adapters for the 5DmkII and the 7D, on our site. Instant Photo Transfer from CF Cameras Thx, Ziv. Eye-Fi co-founder
stackexchange-photo
{ "answer_score": 7, "question_score": 8, "tags": "wireless, compactflash, eye fi" }
Avoid having Ctrl-X insert first item When I use Ctrl-X, the first item on the list is automatically inserted as a word. This is very annoying as I have to use C-N/C-P or remove characters if this wasn't the result I was after. Is there a way to avoid having C-X insert the best match automatically so I can refine my search quicker? An example: a<C-x><C-p> lists: algorithm ... many, many more ... axiom I would like to then just press `x`, and `axiom` would be the only item in the list. Now it completes to `algorithm` right away.
You'll want :set completeopt+=longest This only inserts the longest common text of the matches, not the full first match. Additionally, you can make the first menu item pre-selected (but not yet inserted), so that a quick `<C-y>` (or even plain `<Enter>`) selects and inserts it. This is all described in Make Vim completion popup menu work just like in an IDE.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "vim" }
What is the Rank.Avg (from Excel) function in Python? What is the Python (pandas) equivalent of rank.avg in Excel? For example, if I want to rank column E from E5:E30 in Excel, I can use rank.avg(E5, E5:E30). Thanks!
Sample Date: df = pd.DataFrame(data={'Animal': ['fox', 'Kangaroo', 'deer', 'spider', 'snake'], 'Number_legs': [4, 2, 4, 8, np.nan]}) df Rank function: df['default_rank'] = df['Number_legs'].rank() df['max_rank'] = df['Number_legs'].rank(method='max') df['NA_bottom'] = df['Number_legs'].rank(na_option='bottom') df['pct_rank'] = df['Number_legs'].rank(pct=True) df Output: ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "python, excel, pandas, calculated columns, rank" }
Deleting Pre-Packaged Tomcat WebApps I currently work on an excruciatingly slow remote machine and on Tomcat. So, I was wondering, Tomcat comes with some pre-packaged webapps like: docs examples host-manager manager ROOT Now I just wanted to know, can I delete `docs` and `examples` from the webapps folder without harming the server? I would assume that the other three webapps do serve some important purpose. All in all, if I do remove them, it will save me about 2.5 minutes on average every time I start the server.
1. You can safely remove `docs`, `examples`, `host-manager` and `manager` if you don't use them. 2. The `ROOT` application is almost empty. Removing it entirely can cause some small bugs in some valves (e.g. `RewriteValve`), but you can replace it with an empty directory. You should also consider other ways to speed up Tomcat's start up. If the server is a virtual server (without physical devices), entropy gathering might be a big problem.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 0, "tags": "tomcat, tomcat9" }
Обучалка пользователей интерфейсу на сайте Наверняка каждый натыкался на сайт при посещении в первый раз которого, темнел экран и загорался только какой то конкретный элемент на сайте с выводом сообщения о том что это за элемент и для чего он, как им пользоваться. Этакое обучение сложному интерфейсу сайтов. Помогите пожалуйста найти примеры таких сайтов. Возможно кто то знает как такое называется, есть ли какие то наработки для создания такого обучения на сайте или это всё исключительно с нуля на js+css писать?
Это называется экскурсия по сайту или тур по сайту и другими похожими названиями ) Например тут: 1. < 2. < 3. (вроде похожий тур как во 2 пункте) 4. <
stackexchange-ru_stackoverflow
{ "answer_score": 4, "question_score": 6, "tags": "javascript, html, css" }
Ring Homomorphism from $\mathbb{Z}_m$ to $\mathbb{Z}_n$ Suppose $R$ is a ring homomorphism from $\Bbb{Z}_m$ to $\Bbb{Z}_n$ , prove that if $R(1) = a$ then $(a^2)=a$. Also show, its converse is not true. The first part goes like this : $R(1) = a , R(1\cdot 1) = a$, $R(1) \cdot R(1) = a$ { since R is a ring homomorphism } so , $a\cdot a = a$ or $(a^2)=a$ ; Kindly help me with the converse part....
In $\mathbb{Z}/6$, $3^2=3$. But, we cannot have a map $\mathbb{Z}/5\to \mathbb{Z}/6$ such that $f(1)=3$, because $5\cdot 3=3$ in $\mathbb{Z}/6$, but $5\cdot 1=0$ in $\mathbb{Z}/5$.
stackexchange-math
{ "answer_score": 1, "question_score": 2, "tags": "abstract algebra, ring theory" }
How to make jquery load() in external javascript function? i'm trying to create my own tool in javascript, which will help me load some php functions/files into my div. Here is my javascript: $(document).ready(function () { $('.btn').click(function() { $('#someid').testit(); // $('#someid').load('somefile'); it works return false; }) }); function testit() { $(this).load('somefile'); } And my html: <div id="someid"></div> <form> <input type="submit" value="test" class="btn" /> </form> I can't load the resource from external function - why is that?
If you want to call something like: $('#someid').testit(); Then, you have to create a jQuery plugin that defines the method `testit`. That code would look something like this: jQuery.fn.testit = function() { return this.load('somefile'); } Then, and only then can you use `testit()` as a jQuery method like this: $('#someid').testit(); And, it will operate on the desired selector. Here's some of the jQuery doc on writing plugin methods like this.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, jquery" }
When a React context state updates does it force a rerender of the child components if its context is not being used? Just asking before I actually dive into this as this will rewrite a bunch of navigation logic. Can I have the following structure where I have a list screen and an edit screen as follows <DataProvider> <Navigator> <Screen name="list" component={ComponentThatUseData} /> <Screen name="list different layout" component={ComponentThatUseData} /> <Screen name="list another different layout" component={ComponentThatUseData} /> <Screen name="edit" component={ComponentThatDoesNotUseData}> </Navigator> </DataProvider> If `DataProvider` has a `useState` and I update that will it cause a re-rendeer of the edit screen even though the `useContext` is not invoked? Since a re-render will cause my edit form to lose focus.
Yes, based on what I understand on the React Documentation, one of the caveats of React Context is that when the state in the Context is updated, the children will be affected, I think it's because the Context Provider is still a React Component. React Context Caveat - Section
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "reactjs, react context" }
Why does a manual mount set different file ownership? I've been using the terminal for almost everything: in fact, I often don't even log in through the interface, I use the `tty1` and go to the web with text-browsers. So, the external drive doesn't auto-mount, and I use `sudo mount /dev/sdb1 /mnt/JMCF125_DE` to mount it. It works, but listing shows there's a difference. The files' description when auto-mounting via the GUI (Unity on Ubuntu) looks like: -rw------- 1 jmcf125 jmcf125 In manual mount, the same files' properties look like this: -rwxrwxrwx 1 root root Which makes sense since I had to use `sudo` to mount. But how come the system doesn't have to? How can my mounts work exaclty like the systems'? Also, I heard every action in the GUI goes through a background shell: can I see what commands are printed there?
The default GUI uses Gvfs to mount removable drives and other dynamic filesystems. Gvfs requires D-Bus. You can launch D-Bus outside of an X11 environemnt, but it's tricky. If you have D-Bus running, you can make gvfs mounts from the command line with gvfs-mount. The program `pmount` provides a convenient way to mount removable drives without requiring `sudo`. Pmount is setuid root, so it can mount whatever it wants, but it only allows a whitelist of devices and mount points so it can safely be called by any user. It is not true that every action in the GUI goes through a background shell. A few do but most don't.
stackexchange-unix
{ "answer_score": 3, "question_score": 4, "tags": "ubuntu, permissions, mount, automounting" }
how to add a link of other apps in a current app I have a bunch of similar apps which the user might be interested in downloading. I have a button 'get more of this' so when the user clicks on this button , it shows a link of other apps. Clicking on that link should take him to the download page in the android market. I tried google but couldn't find any answers. Can someone help? Thanks
Try something like this for each app: Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=your.app.package.name")); marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(marketIntent); You can also do a search: Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:your.app.package.name"));
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "android" }
Segment of $\mathbb{R}^2$? I don't understand this sentence; The segment $(a,b)$ can be regarded as both a subset of $\mathbb{R}^2$ and an open subset of $\mathbb{R}^1$. If $(a,b)$ is a subset of $\mathbb{R}^2$, it is not open, but it is an open subset of $\mathbb{R}^1$. What is 'segment $(a,b)$ in $\mathbb{R}^2$'?
That sentence is a good example of poor use of mathematical statements. I guess they meant the set $$\\{(x,y_0)\in\Bbb R^2\;:\;a< x< b\,\,,\,y_0\in\Bbb R\,\,\text{fixed}\\}$$ Taking $\,y_0=0\,$ above gives an interval on the x-axis in the plane...
stackexchange-math
{ "answer_score": 4, "question_score": 3, "tags": "real analysis, general topology" }
How to include video chat in ios app? I'm just creating an app and I wanna include a video chat on it. I haven't seen before an app that uses video chats and I don't know if it's possible. Thanks.
You may be able to use skype. Hopefully this link will help.
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 0, "tags": "ios, iphone, videochat" }
Mod_Rewrite file to subfolder in .htaccess I'm trying to redirect a folder to a file. I want to redirect: > www.mysite.com/category/customername AND > www.mysite.com/category/customername/ TO > www.mysite.com/category.php?customer=customername This is working, but "customer" become "customername.php" and not "customer" Options +FollowSymLinks RewriteEngine On RewriteRule ^category/(.*)$ category.php?customer=$1 [L] How could i remove ".php" via .htaccess? Thank you!
You can use: Options +FollowSymLinks -MultiViews RewriteEngine On RewriteRule ^category/([\s\w-]+)/?$ category.php?customer=$1 [L,NC,QSA]
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, apache, .htaccess, mod rewrite, redirect" }
PHP/MySQL update field proportionally I have a betting script, which allows people to 'invest' in it. The table that stores how much and which user has invested, looks like this and is named 'invested': !Invest table Every time someone places a bet and loses for example, it should share out those losses proportionally according to how much someone has invested and likewise if they win. To clarify, since the sum of 'invested' is 0.6 if someone bets 0.6 and wins, both users in the example would lose their investment. Lets say the bet amount is defined in `$wager`. `$win_lose` when "1" means a win and when "0" means a loss. Any ideas on the PHP script for this?
I am CERTAIN that there is a more optimized query and procedure for this, but here is off the cuff code: //! loop through your rows relative to your game Use the sql from this answer to get your percentages: MySQL query to calculate percentage of total column //! then depending on the win/lose case debit/credit the records: $multiplier = ($gameresult) ? -1 * $wager : $wager; foreach($investors as $playerid => $stake) { $val = $multiplier * $stake; $sql = "UPDATE invested SET invested = ROUND(invested+".$val.") WHERE player_id=".$playerid; }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, mysql" }
What is the difference between Nullable<T>.HasValue or Nullable<T> != null? I always used `Nullable<>.HasValue` because I liked the semantics. However, recently I was working on someone else's existing codebase where they used `Nullable<> != null` exclusively instead. Is there a reason to use one over the other, or is it purely preference? 1. int? a; if (a.HasValue) // ... vs. 2. int? b; if (b != null) // ...
The compiler replaces `null` comparisons with a call to `HasValue`, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.
stackexchange-stackoverflow
{ "answer_score": 563, "question_score": 513, "tags": "c#, .net, null, nullable" }
How to print formatted BigDecimal values? I have a `BigDecimal` field `amount` which represents money, and I need to print its value in the browser in a format like `$123.00`, `$15.50`, `$0.33`. How can I do that? (The only simple solution which I see myself is getting `floatValue` from `BigDecimal` and then using `NumberFormat` to make two-digit precision for the fraction part).
public static String currencyFormat(BigDecimal n) { return NumberFormat.getCurrencyInstance().format(n); } It will use your JVM’s current default `Locale` to choose your currency symbol. Or you can specify a `Locale`. NumberFormat.getInstance(Locale.US) For more info, see `NumberFormat` class.
stackexchange-stackoverflow
{ "answer_score": 160, "question_score": 130, "tags": "java, formatting, bigdecimal, number formatting" }
Merge 2 dictionaries, and try to update the sum if there is common keys? I have two dictionaries, and I need to combine them. But if a key is in both dictionaries, the new value must be the sum of the previous two. That is what I tried: dict1 = { "Elizabeth Alexandra Mary": 250000, "Barack Hussein Obama II": 1750000, "Zhang Aiqin": 1000, "Dean Craig Pelton": 1000000, } dict2 = { "Christopher Larkin": 50000, "Eyal Shani": 5000, "Dean Craig Pelton": 2500000, "Sheldon Cooper": 15600000 } dict1.update(dict2) print('Updated dictionary:') print(dict1) But the value of Dean Craig Pelton is 2500000 and not 3500000 as I wanted. How can I fix this?
Other suggestions will work. But if you want to try this more Pythonic way: (or _just being lazy ._.. ;-) from collections import Counter d3 = Counter(dict1) + Counter(dict2) print(d3) # to confirm it > **Output:** Counter({'Sheldon Cooper': 15600000, 'Dean Craig Pelton': 3500000, 'Barack Hussein Obama II': 1750000, 'Elizabeth Alexandra Mary': 250000, 'Christopher Larkin': 50000, 'Eyal Shani': 5000, 'Zhang Aiqin': 1000})
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 1, "tags": "python, dictionary" }
JOIN 3 QUERIES as a single table/view How can I JOIN these 3 queries in to a single view SELECT A,B,C FROM TABLE1 SELECT D,E,F FROM TABLE 2 WHERE G = 'TOM' SELECT H,I,J FROM TABLE 2 WHERE G = 'HARRY' OUTPUT TABLE/VIEW: A,B,C,D,E,F,H,I,J
This is what worked for me. SELECT A,B,C from T1 LEFT JOIN (SELECT D,E,F FROM T2 WHERE G ='TOM') ON T1.A = T2.D LEFT JOIN (SELECT H,I,J FROM T2 WHERE G = 'HARRY') as T3 ON T1.A = T3.H
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "sql, google cloud platform" }
How can I deploy a new ssh key to hosts after adding it in the maas admin account? I generated a new ssh rsa key pair. I added the public key to the MAAS Admin "user preferences" => "SSH keys". How do I push that new key to the maas nodes?
I don't think MAAS has the ability to push a new key to an already-deployed node. Are you sure there was not a single key imported to your account when you deployed the node?
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 0, "tags": "maas" }
.NET Core Hosting Bundle As far as I understood the Docs, the `.NET Core Hosting Bundle` installs the .`NET Core Runtime`, `.NET Core Library` and the `ASP.NET Core Module`. It seems that there's a Bundle for every version of the .NET Core Runtime (`2.0.6`, `2.0.7`, ...). If I have a self contained deployment of my app, I still need the ASP.NET Core Module. However I don't see that the Module can be downloaded separately without the full bundle. Is there a place where I can download it ? If not: What's the point of having a self contained application, if I still need to install the whole .net core sdk/runtime bundle on my IIS Server?
There is no official download of the ASP.NET Core Module for IIS ("ANCM"), though it can be installed by calling the hosting bundle installer with `OPT_INSTALL_LTS_REDIST=0 OPT_INSTALL_FTS_REDIST=0` as arguments (at least for 1.0-2.0 installs). > What's the point of having a self contained application, if I still need to install the whole .net core sdk/runtime bundle on my IIS Server? Apart from the installer being able to install only ANCM, do not forget that IIS is not the only hosting option for ASP.NET Core Applications. People may still opt to host it on linux or as a Windows Service. Either being exposed to the public Internet (which is supported from 2.0+) or behind NGINX/Apache/… It is also very useful to deploy preview, daily or custom builds of any component inside .NET Core / ASP.NET Core if needed.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 8, "tags": "asp.net core, .net core, asp.net core 2.0" }
Coming from svn background, what should I watch out for in Perforce? What concepts etc in perforce are different from svn in ways that are likely to give me problems? (I am not interested in witch is best, as it not for me to decide what system my new employer uses)
Few points which comes to my mind * svn maintains a copy in its .svn (hence a little slower) to do local operations like svn st, info, etc. but perforce would require a connecion to the server for every operation. * svn checkout is not the same in perforce. You might have to define a workspace and view to do a checkout. * You need to tell perforce that you are going to edit a file before editing it. * Do not edit any perforce file without network(connection to p4 server) your server might not recognize these changes when you try to commit it. * Perforce has better merge/branching capabilities. * You can have only one workspace in your perforce which is different from having multiple working copy in svn.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "svn, perforce" }
How to read HDF5 attributes (metadata) with Python and h5py I have a HDF5 file with multiple folders inside. Each folder has attributes added (some call attributes "metadata"). I know how to access the keys inside a folder, but I don't know how to pull the attributes with Python's `h5py` package. Here are attributes from HDFView: Folder1(800,4) Group size = 9 Number of attributes = 1 measRelTime_seconds = 201.73 I need to pull this `measRelTime_seconds` value. I already have a loop to read files: f = h5py.File(file, 'r') for k, key in enumerate(f.keys()): #loop over folders #need to obtain measRelTime_seconds here, I guess
Ok, I find my answer. To read it You can simply check the name of the attribute as f['Folder'].attrs.keys() and the value can be returned with f['Folder'].attrs['<name of the attribute>']
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 6, "tags": "python, python 3.x, metadata, hdf5, h5py" }
Ranking users as numbers between 1 and 10 +-------+--------+----------+ | likes | shares | comments | +-------+--------+----------+ | 2 | 3 | 1 | +-------+--------+----------+ | 0 | 0 | 1 | +-------+--------+----------+ | 20 | 100 | 4 | +-------+--------+----------+ The above table represents stats about users, thousands of them. The strongest user is the one with the highest `sum(likes + shares + comments)` I want to rank the users between 1-10 with fractions if needed. How can I normalize each row to be a number between 1 - 10. If it helps. I calculate it in a programing language... (nodejs). Thakns
For each user, you can define the proto-score of the user as the sum of all likes, shares and comments. Then, define the score of the user as the proto-score of the user, divided by the max proto-score overa all users, and multiplied by 10. So, in your case above, the proto-scores of the users are $6, 1, 124$, and the scores are $10\cdot\frac{6}{124},10\cdot\frac{1}{124},10\cdot\frac{124}{124}$. * * * With a formula, if you have users $u_1,\cdots u_n$, and $l(u), s(u), c(u)$ is the number of likes, shares and comments of user $u$, then the total score of user $u_i$ is $$10\cdot \frac{l(u)+s(u)+c(u)}{\max_{i\in\\{1,2,\dots,n\\}}\\{l(u_i)+s(u_i)+c(u_i)\\}}.$$ * * * A python program calculating the scores would be something like scores = [likes(user) + shares(user) + comments(user) for user in users] max_proto_score = max(scores) return [10 * score / max_proto_score for score in scores]
stackexchange-math
{ "answer_score": 2, "question_score": -1, "tags": "real analysis" }
How to import VBScript macros into Excel workbook? I have several Excel workbooks. They all share the same macro modules. What I would like to achieve is when editing one module in one workbook not to have to edit the same module in the other workbooks. Naturally, my first step was to export on save the modules in .bas files. But the problem is that I cannot import them on load. I had tried this: Private Sub Workbook_Open() Set objwb = ThisWorkbook Set oVBC = objwb.VBProject.VBComponents Set CM = oVBC.Import("C:\Temp\TestModule.bas") TestFunc End Sub There is a TestModule.bas in the same dir with content: Function TestFunc() MsgBox "TestFunc called" End Function When the workbook is opened, a compile error appears: `Sub or Function not defined`. If I manually import the module everything works just fine. Thanks for any advice.
Like you, I couldn't get the import to work from the workbook_open. You could put your import code in a sub a separate module, and call it from your workbook_open like this: Private Sub Workbook_Open() Application.OnTime Now, "ImportCode" End Sub That seemed to work for me (a direct call did not...)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "excel, vba, vbscript, import" }
Clear items selected from ListBox I am trying to create a simple form using an Excel macro. This form will be used to input data which will be stored in Sheet2. Once the data has been saved, I would like to clear the contents from the form. I have been able to achieve this for most of the input boxes except for listbox. Below is the code that through which I am trying to achieve this functionality. Dim clearlstbox As Long With AOI For clearlstbox = .ListCount - 1 To 0 Step -1 If .Selected(clearlstbox) = True Then .RemoveItem clearlstbox End If Next clearlstbox End With ' 'For clearlstbox = AOI.ListCount - 1 To 0 Step -1 ' If AOI.Selected(clearlstbox) = True Then ' AOI.RemoveItem (clearlstbox) ' End If 'Next With both the codes it throws a similar error message "runtime error '-2147467259 (80004005) unspecified error"
To deselect all the items in a list box For clearlstbox = 0 To AOI.ListCount - 1 AOI.Selected(clearlstbox) = False Next
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "vba, excel, listbox" }
Removendo Carácter específico php/mysql Como remover carácter específico * (ASTERISCOS) de um campo do banco de dados? Existe uma coluna no banco que possui informações e no início e no fim de cada palavra possui vários **asteriscos** esses por sua vez são usados para inserir como **NEGRITO** ao ser enviado uma mensagem para whatsapp. Mas também preciso mostrar o conteúdo dessa coluna em uma tabela html porém quero remover esses * Já tentei com SUBSTRING mas não deu certo pois o conteúdo não é padrão e hora funciona, hora a consulta não é eficaz. Por ex: Ex:01 Esse * texto * é uma frase de * teste * Ex:02 Hoje o * faturamento * foi * menor * Sendo assim a consulta usando SUBSTRING não é eficaz pois as posições pode mudar. Alguém poderia me mostrar uma solução pra esse caso? Lembrando que os caracteres que preciso remover são todos os * que por ventura possa aparecer.
$teste = "Olá * mundo * mais * bonito"; $replace = str_replace("*", "9", $teste); echo $replace; Explicação: O str_replace() irá substituir todas as ocorrências do caracter que você quer em uma string. Você poderia usar outra função do php para trocar somente um determinado número de carácter, porém, percebo que você não quer isso. Outra forma de fazer que irá lhe ajudar muito é usando o RegExp(Expressão Regular). Peço que estude sobre ela, pois existem vários casos que só ela irá ajudar de uma forma ideal.
stackexchange-pt_stackoverflow
{ "answer_score": -1, "question_score": -3, "tags": "php, javascript, mysql, sql, query" }
A programming environment with purely stack-based memory? Many programming languages and Operating Systems have means of providing _dynamic_ memory: `new`, `malloc`, etc. What-if: a program is restricted by using only _stacks_ , with predefined (i.e. compile-time) sizes, stacks cannot grow or shrink _dynamically_. All data is "inside", or "on", these stacks. The program consists of stack manipulations: given a reasonable amount of registers and operations (let's say Intel IA-32, for the sake of specificity). What are the limitations of using this hypothetical system? (e.g. what algorithmic problems can be solved, and which ones can't?) For instance: can this program practically do networking, I/O, cryptography or (G)UI?
In the theory of computation, such computers would still be Turing equivalent (at least in the sense that real RAM computers are... even they have a limit to the amount of memory). A machine with two stacks (of arbitrary, though perhaps not infinite) capacity would suffice. Note: this is for expressing algorithms, not doing I/O. Really, with finite memory, you can't accept non-regular languages (I.e. Solve all algorithmic problems)... Meaning that your hypothetical computer, and real computers, can only accept regular languages (and only certain ones of those!) if finite memory is assumed. Since we have lots of memory, this problem is normally ignored.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "language agnostic, stack" }
Qual a significado da expressão "o que é mais"? > Assim como no fogo se prova o ouro e a prata, assim também nessa longa hora, em que o pai ou marido leva a bocejar, coçar a cabeça, passear pela sala e Consultar o relógio, fica-lhe provada a santa virtude da paciência, e, **o que é mais** , são-lhe de justiça descontados boa meia dúzia de seus pequenos pecados. Qual o significado da expressão "o que é mais" no trecho acima? Obrigado desde já.
**"o que é mais"** é pouco usado em pt-BR. Eu diria **"além do mais"** , que é idiomático e de uso corrente. > * "além do mais" \- expressão usada para acrescentar algo ao que já foi dito. = além disso, aliás, ademais. >
stackexchange-portuguese
{ "answer_score": 1, "question_score": 1, "tags": "significado, significado em contexto" }
Crossing of Brownian Motion Sample Paths I would like to ask for a more rigorous statement and proof of Lemma on page 5 of this paper. In essence, it states that two distinct sample paths of a Brownian motion does not strictly cross (meaning once they intersect at some time, they merge together from then on) with probability $1$. They claim this stems from the Markov property of the Brownian motion which stipulates that a path is uniquely determined by its initial position. This seems strange to me. All the sample path starts from $0$ at time $0$. If the statement is true, then there would have been only one path and the process would have been deterministic. Also Markov property in essence states that the conditional probability depends not on the historical but the current state. It does not seem to say two paths can not start from the same point. Can someone resolve this confusion?
I think you misunderstood the meaning there. They talked about "contingent" claims, these are random variables **given** some other process. A simple example will be something like this: you have a simple SDE, $dX = dB$, with $X_0 = a$, the (strong) solution is, of course, $X_t = a+ B_t$. Now, you have another process on the same Brownian Filtration: $dY = dB$, with $Y_0 = b$, and so, $Y_t = b+B_t$ If $b>a$, then $Y_t>X_t$, **for any given underline sample path $B_t(\cdot)$**.
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "stochastic processes, brownian motion, markov process" }
Line plot with two y-axes using matplotlib? I have a list of (x,y) values like below. > k = [(3, 6), (4, 7), (5, 8), (6, 9), (7, 10), (7, 2), (8, 3), (9, 4), (10, 5), (11, 6)] I would like create a plot that draws lines on opposite axes like below with the assumption that the axis values are in the range 1-15. Please find the figure here ![]( I tried using twinx and twiny, but not exactly sure how to achieve this. I think it might be easier to do using Microsoft Excel, but I have all my values in python npy files.
It could be simple : import matplotlib.pyplot as plt [plt.plot(d) for d in k] plt.ylabel('some numbers') plt.show() gives me : ![enter image description here]( And with the labels : import matplotlib.pyplot as plt [plt.plot(d) for d in k] plt.ylabel('some numbers') ax = plt.gca() ax.xaxis.set_ticks([0,1]) ax.xaxis.set_ticklabels(["BaseLine", "FollowUp"]) plt.show() ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, matplotlib, plot" }
expl3: Expand every item once when adding to a clist I want to add items to a clist and expand every item once. But the (to my eyes) natural `\clist_set:No` didn't work as expected as it expanded only the first item. \documentclass{article} \usepackage{expl3} \begin{document} \ExplSyntaxOn \def\testa{blub} \def\testb{blabla} \clist_set:No\mylist{\testa,\testb} \clist_show:N\mylist \ExplSyntaxOff \end{document} The comma list \mylist contains the items (without outer braces): > {blub} > {\testb }. So what is the correct way to do this? Does one really have to use some loop?
The `o` variant just expands the first token after the brace. You have to add the items one by one: \clist_new:N \l_ulrike_mylist_clist \clist_map_inline:nn { \testa , \testb } { \clist_put_right:No \l_ulrike_mylist_clist { #1 } } Of course you can build your syntactic sugar for this. \cs_new_protected:Nn \ulrike_clist_set_exp:Nn { \clist_clear:N #1 \clist_map_inline:nn { #2 } { \clist_put_right:No #1 { ##1 } } }
stackexchange-tex
{ "answer_score": 4, "question_score": 6, "tags": "expl3" }
Electrons fly on certain orbits around nucleus. why do not they radiate waves and crash to the nucleus? How to fill the gap between classical physics and quantum physics?
Adopting Planck's idea of quantized energy levels, Bohr hypothesized that in a hydrogen atom there can be only certain values of total energy (electron kinetic energy plus potential energy) for the electrons. These allowed energy levels correspond to different orbits for the electrons as it moves around the nucleus, the larger orbits associated with larger total energies. Bohr assumed that an electron in one of these orbits does not radiate electromagnetic wave. For this reason, the orbits are called stationary orbits or stationary states. Bohr recognized that radiation-less orbits violated the laws of physics. But the assumption of such orbitals was necessary because the traditional laws indicated that electron radiates electromagnetic waves as it accelerates around a circular path, and the loss of the energy carried by the waves would lead the the collapse of the orbit.
stackexchange-physics
{ "answer_score": 1, "question_score": 1, "tags": "atomic physics" }
How to run a Minecraft Bedrock Dedicated Server on macOS Big Sur How can I run a Minecraft Bedrock Dedicated Server (Ubuntu version) on macOS Big Sur? I need the server to run while still running macOS (I don't want to install Ubuntu as my main OS). I also would like the server to keep running without my screen being on.
Docker is your best bet. Also easier to configure and you'll be able to squeeze much more performance of your server comparing to VB. There’s a great container that I use: < I’ve been running a Bedrock server since 2019 on a spare MacMini (macOS High Sierra with 4GB RAM!) have a nice little, international community built around it over the years (always the same world :-). Up to Minecraft version 1.18 it was kinda playable for few players at the same time but 4GB ram and an old i5 processor are no longer up to the task I’m afraid. I am trying to get it working on my old i7 macbook pro now but facing some networking issues. Having said that you will need to tinker with the network settings a bit to get the server working on a Mac, especially if you want it to be accessible over internet. The Github project maintainer and other contributors always been supper-helpful tho. <
stackexchange-superuser
{ "answer_score": 0, "question_score": 2, "tags": "macos, minecraft, macos bigsur" }
Como tornar um campo unique para cada foreign key? Estou estudando mysql e me deparei com a seguinte situação e gostaria de saber se há uma solução estruturando minhas tabelas para resolver isso. Supondo que eu tenha duas tabelas; usuario (id, usuario, senha) e anotacoes(id, titulo, texto, id_usuario). Na tabela anotacoes 'id_usuario' é uma foreign key. Eu gostaria que o conteúdo do campo 'titulo' da tabela 'anotacoes' fosse único para cada foreign key. Obrigado desde já!
Se for via comando basta utilizar este comando para adicionar uma _constraint_ de unique composta: ALTER TABLE Persons ADD CONSTRAINT UC_Person UNIQUE (ID,LastName); Se for via `SGBD` basta editar a tabela, selecionar os campos e marcar a opção `Única` (`Unique`).
stackexchange-pt_stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "mysql, sql" }
Does my jenkins slave need to have a user named Jenkins? Jenkins builds started to fail today with the following error. error MSB4175: The task factory "CodeTaskFactory" could not be loaded from the assembly "C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Build.Tasks.v12.0.dll". Could not find a part of the path 'C:\Users\Jenkins\AppData\Local\Temp\05all4b4.tmp'. A similar but slightly different error occurs if I try to build with msbuild14. The C:\Users\Jenkins path does not exist and I'm not aware of ever having a user named Jenkins on the build machine. I think that is clearly part of the problem, but I see nothing in Jenkins master-slave configuration docs that suggest that I need to create a special user account named Jenkins. How can I resolve this error? I'd appreciate if anyone that might have seen this issue in the past could tell me how it was fixed in that situation. The master and slave machines are windows servers.
Here is how I resolved the issue in my case. For some reason I had to recreate the following directory structure. C:\Users**Jenkins\AppData\Local\Temp** The Jenkins user directory had been deleted somehow. There is no Jenkins user account, and the sub-folders under Users is typically for user accounts so I would have never guessed that such a directory would need to exist. Using the error message I just recreated the path, and then gave a jenkins service account full control, recursively, starting at that Jenkins directory. To answer my own question, it appears that a user account named jenkins is not needed but somehow during the slave setup that path gets created with the correct permissions. If that path gets deleted for some reason, then the jenkins service cannot recreate it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jenkins, msbuild" }
Leanback library support for API level 19 Android for TV app? Is there a Leanback library support for API level 19 of Android? In this link < Google says it supports API level 21+. So I am not sure if there's a support for API level 19.
LeanBack was introduced in the support library `v21` so no it is not in v19 < if you are asking if you can use this in android version 19 aka 4.4 yes just use support library v21
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 4, "tags": "android, android fragments, leanback" }
Run VISTA disk check without reboot I want to perform a surface scan on my harddisks (S-ATA, P-ATA, USB and E-SATA) in windows VISTA. Is it possible to do this without scheduling the scan on next reboot? It takes a lot of time and I would like to be able to use the computer during the scan. I can accept that this might not be possible on the window partition disk, but I cannot see why it shouldn't be possible on other disks.
It's as simple as going to the command prompt (with elevation; `start -> search for 'cmd' -> right click -> "run as administrator"`) and typing `chkdsk /x /r D:` (replacing `D:` with the drive you wish to scan.) The `/x` parameter forces a dismount of the drive, and the `/r` parameter forces a surface scan of the drive. Hope that helps!
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "windows, windows vista, boot, check disk" }
How can I filter <li>'s href value inside an UL depending on the value in a textbox? <ul id="ulclass"> <li><a href="#">AAA</a></li> <li><a href="#">BBB</a></li> <li><a href="#">CCC</a></li> </ul> var textBoxValue = //value from textbox $("ul#ulclass").find('li').filter(function() { if($(this).find("a").val() == textBoxValue) return true; else return false; }).css('background-color', 'red'); //optional I'm basically trying to make a basic autocomplete feature. User writes `"A"` to the textbox, jQuery filters each `href text` between `<a>` and `</a>` to match, responses with a custom css styling but it's optional. I'm stuck while filtering them. `filter` function has to be fixed. Any help would be appreciated.
Basic example: var $rows = $('#ulclass li'); $('#search').keyup(function() { var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase(); $rows.removeClass('active').filter(function() { var text = $(this).text().replace(/\s+/g, ' ').toLowerCase(); return val && !!~text.indexOf(val); }).addClass('active'); }); In action: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery" }
The notation $ f \in C^0 ([0,T],X) $ In general, do the notation $$ f \in C^0 ([0,T],X) $$ imply that $\| f(t) \|_X < \infty$ for any fixed $t \in [0,T]$? Or just means $\| f (t) \|_X$ is continuous on $[0,T]$? Here $X$ is like $L^p$ space or Sobolev space.
If $X$ is any sensible space, i.e. a Banach space, then a continuous $f$ sends the compact interval $[0,T]$ to a compact set, which is bounded, hence the $X$-norm of $f(t)$ is always finite.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "functions, partial differential equations" }
Combining a string and integer and printing Given the Below Lists: a = ['abc','cde','efg'] b = [[1,2,3],[2,3,4],[4,5,6]] What is an optimized way to print the output as shown below: Looking for an optimized way as in real I have about 100 x 100 elements. Also keep in mind that each element in b is an integer while in a is a string abc,1,2,3 cde,2,3,4 efg,4,5,6
To print in the exact format you specified: print('\n'.join([a[i] + ',' + str(b[i]).strip('[').strip(']').replace(' ','') for i in range(len(a))])) Output: abc,1,2,3 cde,2,3,4 efg,4,5,6 100*100 element is a very small number for a python program - any optimization at this scale will probably fail to be significant enough for _us humans_ to have noticed. To test: %%timeit array = np.random.randn(100,100) print('\n'.join([str(e) for e in array])) # prints like above result: 148 ms ± 13.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) Also - keep in mind the main bottle neck should be the `print`, not the actual process doing the printing, hence using `zip` or other trick may not work as they don't help the terminal/other stdout capture print fast enough.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "python, list, optimization, printing, iteration" }
get number of rows from last query, Wordpress I am working on a wordpress platform, while generating a mysql query I want to display the number of rows from that query. An example is shown below. $query = ("SELECT wp_posts.ID, wp_term_relationships.object_id FROM wp_posts LEFT JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id WHERE post_date <= '$now' AND term_taxonomy_id = '$catid' AND post_date >= '$then' AND post_status = 'publish'"); Now when I generate this query into phpmyadmin, it gives the following output _Showing rows 0 - 5 (6 total, Query took 0.0013 sec)_ I want to display the number of rows i-e 6 total ... so what function i must use to display it ??
$query = ("SELECT count(*), wp_posts.ID, wp_term_relationships.object_id FROM wp_posts LEFT JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id WHERE post_date <= '$now' AND term_taxonomy_id = '$catid' AND post_date >= '$then' AND post_status = 'publish'");
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, mysql, wordpress" }
What causes "CAdsWatchServerR0::AdsParseSymbol invalid array index" Since a week or so we have the following error popping up at our production machines: CAdsWatchServerR0::AdsParseSymbol invalid array index! The error are generated each plc cycle, filling up the windows event logger, because we forward the events: ![enter image description here]( The errors disappear after a reboot of the PLC, but after some time they reappear. What is the cause of this error? And how can we locate its origin?
Answer from the Beckhoff support: > In the new ADS *.dll the accesses via ADS are better monitored. This message means that you try to access an array index in the controller from a C# or other high level language via ADS, which is not available. > > Example: In the PLC project a `test :ARRAY[0..2] OF INT;` was defined. However, in the high-level language program you want to access e.g. `Test[3]`, which is not defined in the PLC. In our case it turned out to be the HMI (TF2000). There was a user control in the HMI which had a symbol link to an array index which was no longer there.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "twincat, twincat ads" }
Chart JS Custom Labels don't work I am trying to truncate the labels on my horizontal bar chart but can't seem to get the callback to actually work. yAxes: [{ maxBarThickness: 50, gridLines: false, ticks: { padding: 10, callback: value => { let new_label = null; if (value.length > 15) { new_label = value.substring(0, 15) + '...'; } else { new_label = value; } return new_label; }, }, }],
To achieve expected result, use below option of changing value to string using toString() and then just return value bases on length callback: value => { if (value.toString().length > 15) { return value.toString().substr(0, 15) + '...'; //truncate } else { return value } } code example for reference - < **Note** : Check the padding values in the options, check this link for more details - Chart.js y axis labels are truncated incase of missing truncated values due to padding
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, chart.js, truncate" }
IP Address shortage/Subnetting Facing a problem where we are running out of available network addreses, we are currently on bog standard 192.168.1.x range. Reading about making more ips available and subnets and think i have just about got my head around it. My question is, is it as simple as saying to my router (currently handling dhcp) use ip range 172.16.0.1 / 255.255.254.0 and it should hand out ips from 172.16.0.1 to 172.16.1.255? all of which are able to talk to each other? Or have i got wrong end of stick here? On basis of above is there a way of staying on 192.168.x.x and getting more hosts, we are currently using too many but expansion plans wont see more than another 100 at most in next 5 years. if you need any more detail please let me know. Thanks
RFC 1918 identifies a number of private address ranges, including 192.168.0.0/16. This block includes all addresses from 192.168.0.0 to 192.168.255.255, which ought to be sufficient for your network. You're currently using 192.168.1.0/24, which is a block of 254 addresses. If you subtract a bit from the network mask -- 192.168.0.0/23 -- you'll double your available addresses. Your range will extend from 192.168.0.0 to 192.168.1.255. That corresponds to a "netmask" of 255.255.254.0. You'll get the same thing using 172.16.0.0/23, which is what you've identified in your question. Same number of addresses, just a different range of numbers. Note that according to RFC 1918 that block is bigger; 172.16.0.0/12 includes over 1,000,000 addresses.
stackexchange-serverfault
{ "answer_score": 4, "question_score": 1, "tags": "networking, subnet, dhcp server" }
How can I use content_for to put something in :yield I am in ruby 1.9.2, rails3. So My website has some structures, and I want to put menu in a middle of my webpage. I am doing something like (within application.html.erb file) blahblahblah <div id="menu"> <%= yield :menu %> <div> blahblhablah I have a file menu.html.erb which has menu structure for the site. What can I do if I want to use a file within ./layout folder to be used to be part of that yield :menu? I was wondering, if I have to use content_for for every controller, and within every functions... Btw, menu.html.erb will be different for each controller, so thats why I am yielding it. In conclusion, I just want to include one common shared menu.html.erb pretty much everywhere.
You could do something like this in your views: <% content_for(:menu) do %> <%= render :partial => "/layouts/user_menu.html.erb" %> <% end %> You could try to combine this with `controller.controller_name` (not sure this works for Rails3) and load a different menu for each controller automatically.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "ruby on rails, ruby, ruby on rails 3" }
Possible to open Hammer directly from shortcut? I want to open Hammer(for CS:GO) directly from windows shortcut, without the SDK-launch menu. Is this possible? I've only been able to open the SDK launcher from a shortcut. And, is it possible to open a map directly as well? So, 1 shortcut that opens Hammer, with a specific map inside of Hammer? If there exist a launch option for this, then I can use that!
Yup, its possible. Create a shortcut to the hammer.exe and add the -nop4 parameter. ("D:\Steam Games\SteamApps\common\Counter-Strike Global Offensive\bin\hammer.exe" -nop4)
stackexchange-gamedev
{ "answer_score": 1, "question_score": 5, "tags": "steam, hammer" }
mod rewrite .htaccess query string # Turn Rewrite Engine On RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+)$ $1.php [NC,L] RewriteRule ^watch/([a-zA-Z0-9-_]+) watch.php?m=$1 [NC,L] Okay, so I have this code in my `.htaccess` file, and the result I want to retrieve is: * You can go to the url: ` without retrieving `Object not found` * And the url: ` What I want to retrieve with the second url, is that in my database, the title would say: `Bat-Man` and not `Bat Man`, so I want it to show `-` even if it already was in the database.
`[a-z]` means only match a - z `[A-Z]` means only match A - Z `[0-9]` means only match 0 - 9 `[-_]` means only match - or _ Combined together `[a-zA-Z0-9-_]` matches only those characters. So if you don't really want to limit to those characters, use `.` which matches any character. RewriteRule ^watch/(.+) watch.php?m=$1 [NC,L]
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "php, apache, .htaccess, mod rewrite" }
Open serial (COM1) line on Linux to manage a switch through the console I have connected a switch to a PC with a serial cable, and I want to manage it. What utility can I use to open a serial line and manage the switch through the console? On Windows I used PuTTY (serial line COM1).
Minicom. Look here for some tutorial.
stackexchange-serverfault
{ "answer_score": 6, "question_score": 5, "tags": "console, serial" }
Does interpolation search have a time or space complexity? I have done some research on interpolations space and time complexity and have failed to find any conclusive results. So my question is what is the time and space complexity of the interpolation search? I know it is similar to binary search so but surely it does not have the same time and space complexity as a binary search algorithm? Thank you in advance for your help.
Yes, it's known. * * * ### Time Average case: `log(log(n))` Worst case: `O(n)` ### Space You only need to store the indexes in the list for your search, so it's `O(1)`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "algorithm, search, interpolation" }
xcode - project not building? By mistake I deleted the targets in my iphone project.The project is not building any more. Any suggestion on how can I fix this? thanks
!enter image description here
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "iphone, objective c, ios, xcode" }
how to convert int part and fraction part of a double into two integers in arduino How to convert in Arduino or C for example 30.8365146 into two integers: 30 and 8365146. This problem faces me when i try to send gps data via xbee series 1 which don't allow to transmit fraction numbers, so i decided to split the data into two parts. how can i do this? double num=30.233; int a,b; a = floor(num); b= (num-a) * pow(10,3); output: 30 and 232 !!! the output is not 30 and 233 why and how can i fix it double num=30.2334567; int a,b; a = floor(num); b= (num-a) * pow(10,7); output : 30 and 32767 !!!
Since this problem may involve rounding error, as suggested by the other answers, I would recommend doing the muliplication of your floating point values first, then subtracting. For instance, this code prooduced the output you are looking for: int main() { double num = 30.233; int a,b; a = floor(num); b = num * pow(10,3) - a * pow(10,3); printf("%d",b); num = 30.2334567; a = floor(num); b = num * pow(10,7) - a * pow(10,7); printf("%d", b); return 0; } output: 233 and 2334567
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c, int, double, arduino" }
how to save a an entity which has a foreign key to User in django rest framework? In my django rest framework project, i have a model names Profile and which has a forignkey for the User(to store the third party variables like address etc.). class Profile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) # other user data title = models.TextField(max_length=50, blank=False) contact_number = models.TextField(max_length=12, blank=True) description = models.TextField(max_length=500, blank=True) location = models.TextField(max_length=200, blank=True) What i need to know in how to to write the serializer class and View to create the profile. When the a new user removes from the app, the associated profile should be deleted too. **Problem** : how to write the serializer class and view to create profile.
You can simply do like this(in this code, the user information is taken directly from `request.user` which is the logged in user): class ProfileSerializer(serializers.ModelSerializer): user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) class Meta: model = Profile fields = '__all__' and use generic view to create the Profile: from rest_framework import generics from rest_framework.permissions import IsAuthenticated class UserList(generics.CreateAPIView): model = Profile serializer_class = ProfileSerializer permission_classes = (IsAuthenticated,)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "django, authentication, serialization, django rest framework, foreign keys" }
jquery not getting value from select statement on change This is really odd, but I am probably missing something simple. I have a simple select statement where a user can choose a value. onChange calls a function getDrop2() which currently I am trying to get it to alert me which option is chosen. my html is: <select onChange= "getDrop2()" id = "drop1" > <option value="0">All</option> <option value="1">Alphabetical</option> <option value="2">Brewery</option> <option value="3">Style</option> </select> My Javascript is: function getDrop2(){ var choice = $("#drop1").val() alert(choice); } The output of the alert statement is just blank.
In jQuery, you're better off doing something like: <select id = "drop1" > <option value="0">All</option> <option value="1">Alphabetical</option> <option value="2">Brewery</option> <option value="3">Style</option> </select> With the following JavaScript: $(function(){ $('#drop1').change(function() { var choice = $(this).val(); alert(choice); } }); The idea is that jQuery is now attaching the change function automatically to the select with the id of "drop1" By using this pattern, you've decoupled the HTML from the JavaScript that's doing the business logic.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, jquery, jquery selectors" }
Drag and drop custom object I have 2 controls one one form: list and a tree (specific type names are irrelevant). In the list control I execute DoDragDrop method. As the first argument I pass an object which was data bound to that row. The object implements a specific interface and is marked with Serializable attribute. What I want is to retreive that object in DragEnter/DragDrop event handler of the tree control. I'm using the following code: void TreeControlDragEnter(object sender, DragEventArgs e) { var formats = e.Data.GetFormats(); var data = e.Data.GetData(typeof (IFoo)); } Unfortunately, in result data is null and formats is an one-element array which holds the name of the specific type (implementing IFoo). I assume that I would have to pass exact type name to GetData to retreve the object, but it's not possible as it is a private class. Is there a way to get the object by its interface?
You have to provide the same type as the class that was serialized in the first place. You cannot use an interface or base class of the serialized class because then more than one of the formats might match it and it would not know which one to deserialize. If you have several classes that all implement IFoo and there is an instance of each inside the data object then asking for IFoo would be ambiguous. So you must ask for the exact type that was serialized into the data object. This means you should not place classes into the data object that cannot be deserialized because they are private at the other end.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "c#, winforms, drag and drop" }
request and response in nodejs when you hit the URL const http=require('http'); const fs=require('fs'); var server=http.createServer(getFromClient); server.listen(3000); console.log("server start"); function getFromClient(req,res){ fs.readFile('./index.html','utf-8',(error,data)=>{ console.log(data); console.log("-------------"); var content=data.replace(/dummy_title/g,'Title will be here').replace('dummy_content','Content will be here'); console.log(content); res.writeHead(200,{'Content-Type':'text/html'}); res.write(content); res.end(); }); } When I access localhost:3000, console.log(data),console.log("-------------") and console.log(content) are displayed 4 times in console Could someone explain why it happened?
That is normal - your browser makes more than one call. Most browsers make a call to grab /favicon.ico for example. Try to log the url: console.log(req.url); and you'll see what's being called. Solution to this issue can be checking for request URL if it's fetching favicon.ico or not. Just add _req.url != '/favicon.ico'_ to your code function getFromClient(req,res){ if (req.url != '/favicon.ico') { fs.readFile('./index.html','utf-8',(error,data)=>{ console.log(data); console.log("-------------"); var content=data.replace(/dummy_title/g,'Title will be here').replace('dummy_content','Content will be here'); console.log(content); res.writeHead(200,{'Content-Type':'text/html'}); res.write(content); res.end(); }); } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "node.js" }
Identity Management for UNIX Password synchronisation gives warning I installed "Identity Management for UNIX" on win 2008 r2 active directory. I did this because I wanted to have the unix attributes, so I can link linux computers via ldap to the active directory. I followed this tutorial, which worked fine. But ever since I get the warning Password propagation is not done. Either default encryption key is configured or no UNIX hosts configured to propagate password in my active directory. It is true that password propagation is not done, the passwords are all in active directory. No hosts are configured to propagate passwords. As far as I understand, all password related activities are delegated to active directory directly, sssd does only some caching while the machine is offline. Can I tell AD that it is fine the way it is (is it? I think so, but am not sure), or did I miss some configuration on the client?
Since you don't need the password synchronization functionality you could, either remove the "Password Synchronization" role service using the Server Manager GUI, or from a PowerShell w/ an `Import-Module Servermanager` already run execute the `Remove-WindowsFeature ADDS-Password-Sync` command. (Source: < You'll need to restart the computer for the change to "take", in either case.
stackexchange-serverfault
{ "answer_score": 2, "question_score": 2, "tags": "active directory, sssd" }
Is CSRF possible without Cookies? I have been investigating this for some time, but I haven't found anything to satisfy my curiosity. Is it possible, as a user, to be the victim of a CSRF attack if cookies are disabled. Obviously CSRF depends on the users browser to send the user's credentials with the forged request to the legitimate server. Besides IP addresses, browsers don't automatically send in any other session values do they? In that case, as long as a user can login with cookies disabled, they would be safe from CSRF even on vulnerable websites.
So, you have to ask yourself how does the server know one client from another? In majority of cases, it is the session cookie, but there are other ways as well. Consider an admin application, that is configured to work only if accessed from localhost. Here, the server is trusting the IP Address of the browser. Now, if an attacker creates a page like `<img src=" and somehow gets the administrator to visit his page, you have a CSRF. Other examples include abusing Http basic and digest authentication, as Bruno already pointed out.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 11, "tags": "http, cookies, csrf" }
Sharepoint online lookup field hyperlinks not working We are using SharePoint Online and we have noticed the hyperlinks on lookup fields in a list are not working. These are the links that appear in the list view when you have a lookup field that points to another list, this is an example of the url: If you remove the u002f etc. and generally clean up the URL, it works fine. This has happened to all our sites in every list where we have a lookup field that points to another list/field. This occurs in IE 11 and the latest version of Edge and Firefox I am not sure what caused this to happen?
I've checked two SharePoint online tenants. One with early releases enabled and the other without it. Looks like lookups in tenants with the latest updates are broken now. When we click on them in the Classic Experience the URL is incorrectly formatted which gives us a 404 Error.
stackexchange-sharepoint
{ "answer_score": 1, "question_score": 0, "tags": "sharepoint online, lookup column" }
how to create and customize new unit in rally By default in Rally as a unit for estimation for stories is POINT. I would like to change it to something else, for example to Man days. So in setup-> Work-spaces & Projects -> Workspace1 --edit Change field value "Plan Estimate Units" from "point" to "MD" (Man day). But,.. there is a question, how the system can know that MD it is 8 hours?
The simplest answer is that the system won't know that your unit represents 8 hours. The Rally help site describes plan estimates as: > The amount of effort estimated to complete a single user story. Plan estimates are represented by points, t-shirt sizes, or other systems. They do not correspond to task or man hours. The system doesn't do any conversion of these estimates to or from time.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "configuration, project management, agile, rally" }
How to add total line Dynamic Array formula in excel I would like to get a total line at the end of my dynamic filter formula in excel. The problem is how do I shift the total line when the array grows or shrinks? I always want total at the end of the filtered data. ![enter image description here](
Bit of a stretch, but if you want to do this using excel-formulae then you could try the below: ![enter image description here]( Formula in `E5`: =IFERROR(INDEX(FILTERXML("<t><s>"&TEXTJOIN("</s><s>",0,FILTER(A5:C14,C5:C14>15000),"","Total",SUMIF(C5:C14,">15000"))&"</s></t>","//s"),SEQUENCE(COUNTIFS(C5:C14,">15000")+1,3)),"") I'd advise to keep the 15000 as a reference instead of hardcoded obviously.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "excel, excel formula, office365, dynamic arrays" }
Can't comment the original post I can't comment the original post (red rectangle) and I don't know why. I can comment the other ones. What I can't do: !screen shot
From < ## Who can post comments? > All users may leave comments on their own posts and any answers given to their own questions. **Users with at least 50 reputation may comment on any post**. (There is no reputation requirement to post comments on MSO.) Since your user don't have 50 reputation, you can't, for now. But getting 50 reputation on Stackoverflow is not so hard ;) And don't worry about downvotes. Because upvotes and downvotes different on meta.
stackexchange-meta
{ "answer_score": 1, "question_score": -8, "tags": "support, comments, comment replies" }
Background-image:url not working I am trying to add a background image to a link via the background-image:url like so <a href="#" style="width:300px; height:125px; background-image:url(' I have tried inline CSS as well as external CSS. It works perfectly in a div, but not in an a. I have tried just using background:url also and had no luck with that either. This is a sprite image, and I want to change the position based on a mouse over, but I can't even get the image to appear in the first place. I would really appreciate some assistance :)
The "a" tag is an _inline_ element, change it's display type to block; < <a href="#" style="display:block;width:300px; height:125px; background-image:url(' Because this is a sprite, you will want to move this into an external stylesheet in order to add the pseudo class styles
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "html, css" }
Simple phasor problem with AC Simple problem that I can't solve. On this AC circuit, find the current read by ammeter \$ A_3 \$ (the one in series with the resistor) given that \$A_1\$ reads 4A and \$A_2\$ reads 3A, assuming every current is read by its RMS value. ![Simple AC Circuit]( There are no given values for resistor and capacitor, but the textbook answer gives that \$A_1\$ reads 2.65A Here's what I've tried : Since we're in AC, I figured voltage lags in the capacitor, so current must lead by 90 degrees. I tried using Kirchhoff's law with phasors in mind to find \$I_3 = I_1 - I_2\$ which would give \$4e^{j0} - 3e^{j\frac\pi2} = 4 - 3j\$. However, the magnitude of this phasor is \$5\$, which is greater than the magnitude of \$I_1\$, which is impossible, since there are no current source in branch 2. What am I missing? Thank you
You are correct that the resistor current and capacitor current are out of phase by 90 degrees, but in your solution you assumed that the total current and the capacitor current are out of phase by 90 degrees. The current through \$A_1\$ is the total current and the current through \$A_2\$ is 90 degrees out of phase with the resistor current. If you draw the phase diagram \$A_1\$ is the hypotenuse. Can you use geometry and take it from there?
stackexchange-electronics
{ "answer_score": 2, "question_score": 0, "tags": "ac, phasor" }
How to solve linear system of equations using colt library in java I want to solve the linear equation **matrix*X=D** using Colt library. I tried : DoubleMatrix2D matrix; matrix = new DenseDoubleMatrix2D(4,4); for (int row = 0; row < 4; row++) { for (int column = 0; column < 4; column++) { // We set and get a cell value: matrix.set(row,column,row+column); } } DoubleMatrix2D D; D = new DenseDoubleMatrix2D(4,1); D.set(0,0, 1.0); D.set(1,0, -1.0); D.set(2,0, 91.0); D.set(3,0, -5.0); DoubleMatrix2D X; X = solve(matrix,D); but I get an error "The method solve(DoubleMatrix2D, DoubleMatrix2D) is undefined for the type Test" , where Test is the name of the class. What have I done wrong? Any ideas?...
The reason why you are getting this error is because method `solve()` is non-static and can't be accessed from `main()`. This should solve your problem: Algebra algebra = new Algebra(); DoubleMatrix2D X = algebra.solve(matrix, D);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, matrix, system, linear algebra, colt" }
Java - jdbc select method for multiple columns public void Execute_Select_Statement(String instruction) throws SQLException { PreparedStatement ps = null; try { ps = this.conn.prepareStatement(instruction); ResultSet rs = ps.executeQuery(); while (rs.next()) { String column = rs.getString(1); System.out.println("column1:" + column); } } catch(SQLException e) { System.out.println(e.getMessage()); } finally { if(ps != null) { ps.close(); } } } I now have the code above, which gets a specific column from a table in an oracle database. But when I want to get more columns I have to add another getstring. How can I fix it in a way that it first gets the number of columns of the given table, and then gets the info out of it?
You can use the `ResultSetMetaData.getColumnCount()` method retrieved from the `ResultSet` metadata instance: ResultSetMetaData metadata = rs.getMetaData(); int columnCount = metadata.getColumnCount();
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, mysql, sql, oracle, jdbc" }
How do I implement camera axis aligned billboards? I am trying to make an axis-aligned billboard with Pyglet. I have looked at several tutorials, but they only show me how to get the up, right, and look vectors. So far this is what I have: target = cam.pos look = norm(target - billboard.pos) right = norm(Vector3(0,1,0) * look) up = look * right gluLookAt( look.x, look.y, look.z, self.pos.x, self.pos.y, self.pos.z, up.x, up.y, up.z ) This does nothing for me visibly. Any idea what I'm doing wrong?
I tried out billboards a while back. I just created a quad that faced the camera. Using the position I want the object at and the up and right vectors (normalized) of the camera, you can set the four corners of the quad like so: a = position - ((right + up) * scale); b = position + ((right - up) * scale); c = position + ((right + up) * scale); d = position - ((right - up) * scale); Where `a`, `b`, `c` and `d` define the corners, use them clockwise or counter-clockwise depending on the winding order of your graphics library. The right can be derived from the cross product or the look and the up vectors.
stackexchange-gamedev
{ "answer_score": 2, "question_score": 4, "tags": "opengl, pyglet, billboarding" }
What are the 'hiq' and 'siq' fields in dstat cpu output dstat CPU metrics have two fields named `hiq` and `siq`. What do these fields represent? Are they some sort of hardware interrupts and software interrupts?
They are from `/proc/stat` (< hiq - irq: servicing interrupts siq - softirq: servicing softirqs
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 7, "tags": "metrics" }
Multiple labels on a single bounding box for tensorflow SSD mobilenet I have configured SSD mobilenet v1 and have trained the model previously as well. However in my dataset for each of the bounding box there are multiple class labels. My dataset is of faces each face have 2 labels: age and gender. Both these labels have the same bounding box coordinates. After training on this dataset the problem that I encounter is that the model only labels the gender of the face and not the age. In yolo however both gender and age can be shown. Is it possible to achieve multiple labels on a single bounding box using SSD mobile net ?
It depends on the implementation but SSD uses a softmax layer to predict a single class per bounding box, whereas YOLO predicts individual sigmoid confidence scores for each class. So in SSD a single class with argmax gets picked but in YOLO you can accept multiple classes above a threshold. However you are really doing a multi-task learning problem with two types of outputs, so you should extend these models to predict both types of classes jointly.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "tensorflow, training data, object detection api" }
examples of smooth manifold which is not Hausdorff or not second countable In differential geometry, a Hausdorff smooth manifold whose topology has a countable basis has good property. However, I don't know examples which is smooth but not Hausdorff or not second-countable. Could you teach me a couple of examples? Is there geometrically interesting one?
Hausdorff but not second-countable: Take the product of $\mathbb R$ with its standard topology and $\mathbb R$ with the discrete topology. The intuition here is an uncountably infinite family of copies of $\mathbb R$, all separated from each other. Non-Hausdorff: consider $\mathbb R \times \\{0,1\\}$ and identify $(x,0) = (x,1)$ whenever $x<0$. Around any given point this looks like $\mathbb R$, but the points $(0,0)$ and $(0,1)$ cannot be separated by neighbourhoods.
stackexchange-math
{ "answer_score": 5, "question_score": 1, "tags": "differential geometry, smooth manifolds" }
SLDS classes on (new) base Lightning web components don't work SLDS classes on base Lightning web components do not appear to work... unless I'm missing something? When I view the component below, the margin _is_ properly applied to the div, but _not_ to the card. Am I missing something? Thanks very much! **UPDATE:** Trying `slds-m-around_large` seems to add an arbitrary (and entirely incorrect) amount of margin. It also doesn't even add on the sides, only top & bottom.. not that I want on the sides in this case. **UPDATE 2:** I witness the same (incorrect?) thing in the Web Components Playground. But that can't be the expected behavior, can it? <template> <div class="slds-m-bottom_large"> div </div> <lightning-card class="slds-m-bottom_large"> card 1 </lightning-card> <lightning-card> card 2 </lightning-card> </template> ![screenshot](
By default, custom elements are set to `display: inline`. By introspecting the DOM in the playground, you can also see that the `lightning-card` doesn't override the `display` property from inside using the `:host` selector. The margin and padding are not being applied because the `lightning-card` element is `display: inline`. In order to get the margin and padding working as you expect you will need to set the `lightning-card` display CSS property to `block`. playground lightning-card { display: block; }
stackexchange-salesforce
{ "answer_score": 7, "question_score": 1, "tags": "lightning web components" }
PdfFileReader: PdfReadError: Could not find xref table at specified location I am trying to read Pdf file in python through: from PyPDF2 import PdfFileReader, PdfFileWriter test_reader = PdfFileReader(file("test.pdf", "rb")) Above Line throws error: PyPDF2.utils.PdfReadError: Could not find xref table at specified location Any help will be highly appreciated
It's fixed. Actually, there wasn't any problem. Seems, the pdf I was using to test was corrupted one (even though when I opened it, the content was there, which is why I couldn't figure out at first place) I replaced it with another one and it worked as expected.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 6, "tags": "python, pypdf" }
Compare git commits on different branches I have two branches - master and experimental. How can I see which commits are in experimental and not in master? It would be nice to see this in gitk, but in the terminal is also ok.
You can see that using 'git log' : git log master..experimental That will show you which commits are in experimental but not in master.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "git, gitk" }
Signing requests in Amazon S3 for .NET SDK through HTTP Header I am trying to access Amazon S3 content from a ASP.NET application. I am using AWS SDK kit for .NET. Currently, I am using GetpreSignedURL() function to sign my requests and then I am setting my IFrame src as the URL. s3Placeholder.Text = ListingObjects(); GetPreSignedUrlRequest request = new GetPreSignedUrlRequest() .WithBucketName(bucketName) .WithKey("notebook.htm"); request.WithExpires(DateTime.Now.Add(new TimeSpan(7, 0, 0, 0))); string url = S3.GetPreSignedURL(request); this.Iframe2.Attributes.Add("src", url); The issue is if you have a look at the source of the IFrame you can see the complete string including the access key and signature. I was wondering if there is a better way of doing it through HTTP headers so that the login secure information is not passed through query string.
You cannot use http headers to authenticate the request so the only other potential option to is to proxy any requests through your web server but this gets complicated and removes many of S3's benefits. However, what you are doing is not insecure. The pre-signed url **does not** expose your secret key. It only only shows your key (which does not need to be secret) and the signature (hash) which is generated using the secret key. **You cannot work back from the url to get the secret key.** You can make things even more secure by using Amazons IAM to create a user that only has readonly access to a single bucket and using those credentials to create your urls. That way, even if the attacker somehow manages to reverse engineer your secret key from the url, all they have is readonly access to a single bucket.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "amazon s3" }
How to get opposite direction of `git diff origin/master` If I run `git diff origin/master`, it shows me the changes in my local copy of the files in the repo against the files in the master branch in the remote repository. I know you can list another parameter, and swap the parameters to get the opposite like this: `git diff origin/branch_a origin/branch_b` becomes: `git diff origin/branch_b origin/branch_a` ...but in my case, I want to compare with local (possibly uncommitted) changes. Is there a way to do the opposite of `git diff origin/master`? So basically, the output would be the same, but instead of where it says lines were removed, it would say they were added, and vice-versa. I know I could write a script to parse the text and reverse it, but I figured there must be a way to do it and I just don't know what it is / can't find the manual page on how to do it.
Right: `git diff _commit-specifier_` compares the given commit's tree to the work-tree, with the commit's tree on the "left side" as `a/` and the work-tree on the "right side" as `b/`. As you noted, it's tough to reverse these as the work-tree is implied by the lack of a second tree or commit specifier. Fortunately, `git diff` has a `-R` option to reverse the two sides, so `git diff -R _commit-specifier_` does the trick.
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 7, "tags": "git" }
Different way of expressing variance I am having trouble with the following statement (from one of the answers from SOA exam, don't worry about the question as it has no bearing on the question I am asking). > The marginal distribution of X has probability $1/5 + a$ at $0$, $2a + b$ at $1$, and $1/5 + a$ at $2$. Due to symmetry, the mean is $1$ **_and so the variance is $(0-1)^2 (1/ 5+a ) +(1- 0)^2 (1/ 5 +a) = 2/5+2a$_** I do not recognize this expression for variance from anywhere that I remember. The only one I am familiar with is $${E(X^2)-{[E(X)]}^2}$$ Can somebody please explain to me this other expression that is being used here, $(0-1)^2 (1/ 5+a ) +(1- 0)^2 (1/ 5 +a)$, or even just provide a link?
\begin{align} E[(X-E[X])^2] &= E[X^2-2XE[X]+(E[X])^2] \\\ &=E[X^2]-2E[X]E[X]+(E[X])^2 \\\ &=E[X^2]-2(E[X])^2+(E[X])^2 \\\ &=E[X^2]-(E[X])^2 \\\ \end{align} They use an alternative expression for the variance which is just $E[((X-E[X])^2] $. We have three values, $x_1, x_2, x_3$ where $x_2$ is the mean and $(x_3-x_2)^2=(x_1-x_2)^2$ in this question.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "probability, statistics, probability distributions" }
different versions of abcpdf on the same server I have two versions of abcpdf running on the same machine. One of the projects is using the older version 7.1 and the other one is using the newer version i.e 8.1. When i try to build, the visual studio automatically picks up the latest version on abcpdf 8.1 and throws the following compile error 'WebSupergoo.ABCpdf7.Doc.Doc()' is obsolete: 'Don't use ABCpdf7 namespace - use ABCpdf8 instead.' Please suggest me where i am going wrong. Thanks.
Uninstall both versions from the GAC, and re-start IIS to get them cleared out. Then reference the specific dlls from your projects manually, following the instructions for a manual install: < You will need to point your project references to the two different AbcPdf.dll files (one for each version), and you will need to make sure that either ABCpdfCE7.dll or ABCpdf8-32(or -64).dll is copied to the bin of the correct project.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "visual studio 2010, abcpdf" }
javascript string replacement hey guys just a quick one for tonight. i just want to change a smiley face e.g :-P to a html code like `<span class=surp></span>` but it comes out with a error which is `Uncaught SyntaxError: Invalid regular expression: /:-(/: Unterminated group` this is part of my code newmessage = newmessage.replace(/:-(/gi, "<span class=sad></span>"); i figured it out and it doesn't like the bracket so is there any other way to do this with the bracket?
In a regular expression, `(` begins a group - but in your case you want to match the literal `(`, so you need to escapg it with a backslash: newmessage = newmessage.replace(/:-\(/gi, "<span class=sad></span>"); Besides that, I would make the `-` optional - most people use `:(` instead of `:-(`: newmessage = newmessage.replace(/:-?\(/gi, "<span class=sad></span>");
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript" }
How can a magnetic circuit with an airgap have a higher e.m.f in the secondary coil than the same circuit without the air gap? I have a magnetic circuit with the same configuration as in the image, the primary coil has 203 turns and the secondary has 406 turns, how do I get a higher eletromotive force when there is an air gap across the magnetic circuit? If the reluctance is increased and the permeability is reduced shouldn't the emf also be less than without the air gap? ![enter image description here](
Notice that the primary magnetic field has two places go. The middle iron, and then the iron under the secondary. Any magnetic field in the middle iron is not coupling to the secondary. With no air gap (low reluctance), lots more of the magnetic field gets shunted through the middle iron. Resulting in even less magnetic field coupled to the secondary.
stackexchange-electronics
{ "answer_score": 2, "question_score": 0, "tags": "transformer, electromagnetism, saturation, magnetic flux" }
How to add label to "file upload" input? In my code I have something like this: echo $this->Form->input('name'); echo $this->Form->input('app_code'); echo $this->Form->file('icon'); echo $this->Form->input('description'); And the form looks like this: !enter image description here As you can see, the file input does not have a label like the other input text fields. How can I add one (without having to create the HTML manually)?
$this->Form->input('icon', array('label' => 'Your label', 'type' => 'file')); Relevant info from the book
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "php, forms, cakephp" }
What's the best android phone to get as a developer I know you can get a developer phone but the new G2 looks pretty nice as well as the Samsung around the corner. I would assume however that it would be a better idea to be using a consumer phone if they are the target market for apps you wish to produce, especially for testing purposes. Has anyone else had experience from this choice and provide any further illumination to the issue?
G1. It is the only phone with a hard keyboard. When the keyboard is opened up you will get several events/activity relaunches that will not happen on the touch screen only phones. If you are doing apps it really doesn't matter if you get the dev version or retail one. Going forward, you are probably going to need to get several phones as the hardware diverges. For example the samsung has a 5way instead of a trackball. Depending on how you are using the trackball, that could be a significant difference. But as far as looks, get the samsung. It is by far the best looking android phone that I have seen so far.
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 15, "tags": "android" }
OS X: what Norton Commander clone you can suggest On Windows I'm addicted to Altap Salamander. I've tried a couple of OS X alternatives, e.g. Midnight Commander. Yes, they are better than plain command line or Finder, but can't compare with Altap Salamander. Besides the normal commands known to Midnight Commander, I also miss directory bookmarks or directory history. An acceptable tool does not have to look like a good Mac application -- I'm searching for something powerful for keyboard-centric file management. Can you please share your experiences with other NC clones for OS-X?
Like you, I was hopelessly addicted to Altap Salamander. Unfortunately I've not found anything on Linux or OS X that matches Salamander's speed and ease of use, especially for keyboard navigation. However, there are a couple that come sorta close: Disk Order is my favorite, and by far the closest to Altap in functionality that I've found. XFolders is a close second, though I'd say it's more like NC than Altap (i.e. not quite as modern and full featured) Path Finder seems to be popular, but I didn't like it at all; I found it no better than Finder for most routine file management tasks, although admittedly it is great for some things. MuCommander is pretty nice, but Java-based, so you don't get that native speed
stackexchange-superuser
{ "answer_score": 3, "question_score": 4, "tags": "macos, total commander, midnight commander, norton commander" }
Custom border for glossary and index pages I'm preparing a technical book in Latex using KOMA script `srcbook` class and I would like to add a gray border ONLY to glossary and index pages. The idea is to make them easy to find when the book is closed, like in the sample below: !index page I have seen similar solutions using `fancyhdr` or `tikz` but (1) I don't know if they can be applied directly without screwing KOMA, and (2) I've found no way to limit the border only to index/glossary pages and I'm sure there must be an obvious way to do both things. UPDATE: I found a solution (see below) using the `eso-pic` and `ifthen` packages to draw the border and the `etoolbox` to patch the `theindex` environment and control where it appears.
You can use the package `background` in combination with TikZ and the defined node `current page`: \documentclass{scrbook} \usepackage[]{background} \backgroundsetup{contents={}} \usepackage{lipsum} \usepackage{imakeidx} \makeindex \begin{document} \index{a}\lipsum[1-10] \AddEverypageHook{% \tikz[remember picture,overlay]\drawline width=1cm rectangle (current page.south east);% } \printindex \end{document}
stackexchange-tex
{ "answer_score": 7, "question_score": 6, "tags": "margins, koma script, glossaries" }
Opengl-es camera can see an object? I have a camera (pos, dir) and I have an object (x,y,z) How can I detect when the object can see with my camera?
You don't have enough info. You need to know camera frustum. Than you calculate if the object is inside frustum. Learn more here: < <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "opengl es" }
htaccess, no variable go to allcategories.php I have the htaccess rule above: RewriteRule ^category/([\w-]+)/(\d+)/?$ category.php?categoria=$1&id=$2 [L,QSA,NC] RewriteRule ^category/([\w-]+)/?$ category.php?categoria=$1&id=1 [L,QSA,NC] RewriteRule ^category/ allcategories.php So if I have `category/some_name` or `category/some_name/id` it will redirect to category.php. If I have only `category/`to allcategories.php. The problem is urls like this: category/j.j._name category/victoria%27s_secret It has a value (j.j...) and it is redirecting to allcategories.php instead of category.php. What is wrong? is it the special characters? how to solve?
You need to tweak your regex to allow special characters: RewriteRule ^category/([^/]+)/(\d+)/?$ category.php?categoria=$1&id=$2 [L,QSA,NC] RewriteRule ^category/([^/]+)/?$ category.php?categoria=$1&id=1 [L,QSA,NC] RewriteRule ^category/?$ allcategories.php [L,NC] `[^/]` will match anything except a `/`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": ".htaccess, friendly url" }
Erro localhost Visual Studio O meu VS estava funcionando perfeitamente, hoje comprei e instalei o antivírus kaspersky, quando fui rodar um site ASP.NET(MVC) apareceu o seguinte erro: > UNABLE TO START PROGRAM '' Uma operação não é valida no estado atual. ![inserir a descrição da imagem aqui]( Como resolvo o problema?
Verifique seu Firewall e tente mudar de porta, provabelmente um problema de ISS. Para configurar siga aqui o exemplo: ![CTRL+R]( ![gerir foncionalidades do windows]( ![escolher os programas]( ![aplicar modificacoes]( ![resultado do locahost](
stackexchange-pt_stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "asp.net, asp.net mvc 5, visual studio, entity framework 6, localhost" }