qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
39,427,339 | I am trying to use CSS so when you hover on something it changes background colors. The code I am using does not work though. I can't seem to find out why though. It should work, right?
```css
body {
margin: 0;
font-family: Arial;
font-size: 1em;
}
.navbar-ul, a {
margin: 0;
color: white;
overflow: hidden;
}
li, a {
text-decoration: none;
display: inline-block;
padding: 10px;
background: black;
}
li a :hover {
background-color: blue;
}
li {
list-style-type: none;
float: left;
}
```
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dark Website Template by Jordan Baron</title>
<link rel="stylesheet" href="styles-main.css">
</head>
<body>
<div class="navbar">
<ul class="navbar-ul">
<li><a href="#">HOME</a></li>
<li><a href="#">CONTACT</a></li>
<li><a href="#">ABOUT</a></li>
</ul>
</div>
</body>
</html>
```
Please help! | 2016/09/10 | [
"https://Stackoverflow.com/questions/39427339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
$ awk '{delete a; for(i=1;i<=NF;i++) a[$i]++; if(a["."]>=2) next} 1' foo
A B C D E
0 1 . 0 0
1 ./. 0 1 1
1 1 0 0 0
```
It iterates all fields (`for`), counts field values and `if` 2 or more `.` in a record, restrains from printing (`next`). If you want to count the periods only from field 3 onward, change the start value of `i` in the `for`: `for(i=3; ...)`. | Perhaps this is alright.
```
awk '$0 !~/\. \./' file
A B C D E
0 1 . 0 0
1 ./. 0 1 1
1 1 0 0 0
``` |
39,427,339 | I am trying to use CSS so when you hover on something it changes background colors. The code I am using does not work though. I can't seem to find out why though. It should work, right?
```css
body {
margin: 0;
font-family: Arial;
font-size: 1em;
}
.navbar-ul, a {
margin: 0;
color: white;
overflow: hidden;
}
li, a {
text-decoration: none;
display: inline-block;
padding: 10px;
background: black;
}
li a :hover {
background-color: blue;
}
li {
list-style-type: none;
float: left;
}
```
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dark Website Template by Jordan Baron</title>
<link rel="stylesheet" href="styles-main.css">
</head>
<body>
<div class="navbar">
<ul class="navbar-ul">
<li><a href="#">HOME</a></li>
<li><a href="#">CONTACT</a></li>
<li><a href="#">ABOUT</a></li>
</ul>
</div>
</body>
</html>
```
Please help! | 2016/09/10 | [
"https://Stackoverflow.com/questions/39427339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | With awk:
```
$ awk '{c=0;for(i=1;i<NF;i++) c += ($i == ".")}c<2' file
A B C D E
0 1 . 0 0
1 ./. 0 1 1
1 1 0 0 0
```
Basically it iterates each column and add one to the counter if the column equals a period (`.`).
The `c<2` part will only print the line if there is less than two columns with periods.
With sed one can use:
```
$ sed -r 'h;s/[^. ]+//g;s/\.\. *//g;/\. \./d;x' file
A B C D E
0 1 . 0 0
1 ./. 0 1 1
1 1 0 0 0
```
`-r` enables extended regular expressions (`-E` on \*BSD).
Basically a copy of the pattern space is stored in the `h`old buffer, then all but spaces and periods is removed.
Now if the pattern space contains two separate periods it can be deleted if not the pattern space can be e`x`changed with the hold buffer. | Perhaps this is alright.
```
awk '$0 !~/\. \./' file
A B C D E
0 1 . 0 0
1 ./. 0 1 1
1 1 0 0 0
``` |
39,427,339 | I am trying to use CSS so when you hover on something it changes background colors. The code I am using does not work though. I can't seem to find out why though. It should work, right?
```css
body {
margin: 0;
font-family: Arial;
font-size: 1em;
}
.navbar-ul, a {
margin: 0;
color: white;
overflow: hidden;
}
li, a {
text-decoration: none;
display: inline-block;
padding: 10px;
background: black;
}
li a :hover {
background-color: blue;
}
li {
list-style-type: none;
float: left;
}
```
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dark Website Template by Jordan Baron</title>
<link rel="stylesheet" href="styles-main.css">
</head>
<body>
<div class="navbar">
<ul class="navbar-ul">
<li><a href="#">HOME</a></li>
<li><a href="#">CONTACT</a></li>
<li><a href="#">ABOUT</a></li>
</ul>
</div>
</body>
</html>
```
Please help! | 2016/09/10 | [
"https://Stackoverflow.com/questions/39427339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
$ awk '{delete a; for(i=1;i<=NF;i++) a[$i]++; if(a["."]>=2) next} 1' foo
A B C D E
0 1 . 0 0
1 ./. 0 1 1
1 1 0 0 0
```
It iterates all fields (`for`), counts field values and `if` 2 or more `.` in a record, restrains from printing (`next`). If you want to count the periods only from field 3 onward, change the start value of `i` in the `for`: `for(i=3; ...)`. | With awk:
```
$ awk '{c=0;for(i=1;i<NF;i++) c += ($i == ".")}c<2' file
A B C D E
0 1 . 0 0
1 ./. 0 1 1
1 1 0 0 0
```
Basically it iterates each column and add one to the counter if the column equals a period (`.`).
The `c<2` part will only print the line if there is less than two columns with periods.
With sed one can use:
```
$ sed -r 'h;s/[^. ]+//g;s/\.\. *//g;/\. \./d;x' file
A B C D E
0 1 . 0 0
1 ./. 0 1 1
1 1 0 0 0
```
`-r` enables extended regular expressions (`-E` on \*BSD).
Basically a copy of the pattern space is stored in the `h`old buffer, then all but spaces and periods is removed.
Now if the pattern space contains two separate periods it can be deleted if not the pattern space can be e`x`changed with the hold buffer. |
113,478 | I'm developing a plugin for [Hubot](http://hubot.github.com) (a scriptable chatbot) to take a URL, and display it on a Mac Mini connected to a TV in my office.
However I'm not actually sure how feasible this is. Hubot is able to send messages to APIs using HTTP. Is there a known method of allowing a Mac to listen for requests over HTTP, and then run a command (an applescript or shell script perhaps)? | 2013/12/11 | [
"https://apple.stackexchange.com/questions/113478",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/27983/"
] | Python is shipped with Macs, you can just use [SimpleHTTPServer](http://docs.python.org/2/library/simplehttpserver.html) to respond to HTTP requests. | Depends on what you want to do (and what Hubot can do, which I'm not familiar with) – but it seems it is possible through a combination of iChat/Messages and AppleScript to control a Mac through sending commands to a chat account which are then handled by a special script.
The original script that's provided by Apple can be found [here](https://github.com/FreekKalter/apple_scripts/blob/master/iChat/iTunes%20Remote%20Control.applescript) (it should be preinstalled on any recent Mac), and a how-to for setting it up is [here](http://www.maketecheasier.com/mac-osx-remote-control-your-itunes-via-ichat/). I guess that would be a rather … convoluted solution ;)
Of course, you can also enable "Remote Login" in the Sharing Panel in the System Preferences and then connect to the Mac through SSH – which gives you control over the Mac via the CLI. |
113,478 | I'm developing a plugin for [Hubot](http://hubot.github.com) (a scriptable chatbot) to take a URL, and display it on a Mac Mini connected to a TV in my office.
However I'm not actually sure how feasible this is. Hubot is able to send messages to APIs using HTTP. Is there a known method of allowing a Mac to listen for requests over HTTP, and then run a command (an applescript or shell script perhaps)? | 2013/12/11 | [
"https://apple.stackexchange.com/questions/113478",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/27983/"
] | Python is shipped with Macs, you can just use [SimpleHTTPServer](http://docs.python.org/2/library/simplehttpserver.html) to respond to HTTP requests. | If you activate PHP on your mini and restart Apache, then you can send commands to the web server through http GET and POST commands. Although POST is more secure and the recommended method. I use this method to send commands from an Arduino to a mac and have it store data in a database. If you want to experiment without changing the Apache setup on your Mac then try MAMP, it is free and open source.
PHP is the backend of the internet and can do just about anything you need, (or you can run javascript) to update a web page that will display whatever you want on your TV. |
913,489 | The `REXML` module appears to have support for [RELAX NG validation](http://www.germane-software.com/software/rexml/doc/classes/REXML/Validation/RelaxNG.html), but the docs don't have any real information on using the validation portion of the framework.
How would you validate an XML document with a RELAX NG schema? A code snippet would be most helpful. TIA! | 2009/05/27 | [
"https://Stackoverflow.com/questions/913489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] | One option I've thought of is to use POP3's UIDL command, and have a table in SQL Server with a unique column of UIDLs that were already processed.
Then, before downloading each message, the daemon would INSERT the UIDL into the table, and, if it got an error, skip the message. (I'm assuming that SQL Server's INSERT command is an atomic operation). | First I must admit I do not know what commands POP3 supports, but... if you can do an explicit 'DELE' and get an error if the message no longer exists, then I'd say:
* RETR the message
* DELE the message
* Process only if DELE succeeded
EDIT:
After reading RFC1939, this approach should work; from the RFC:
```
DELE msg
Arguments:
a message-number (required) which may NOT refer to a
message marked as deleted
Restrictions:
may only be given in the TRANSACTION state
Discussion:
The POP3 server marks the message as deleted. Any future
reference to the message-number associated with the message
in a POP3 command generates an error. The POP3 server does
not actually delete the message until the POP3 session
enters the UPDATE state.
Possible Responses:
+OK message deleted
-ERR no such message
Examples:
C: DELE 1
S: +OK message 1 deleted
...
C: DELE 2
S: -ERR message 2 already deleted
```
This is ofcourse assuming that the Gmail implementation actually honours the RFC. |
101,609 | Acme Co. screens and places candidates at other companies including those fictionally-named Bravo and Tec2.
Candidate J. Doe applies for a role with Bravo, including a resume citing a lot of experience on a project at Tec2.
Acme learns that this is a serious misrepresentation, through a combination of its own knowledge resulting from the partnership with Tec2 and J. Doe's performance on interview questions that should have been easy if the resume was truthful.
Beyond simply declining to hire the candidate, does Acme have any further ethical responsibilities? | 2017/10/27 | [
"https://workplace.stackexchange.com/questions/101609",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/37509/"
] | Literally any employer could find this out by
* contacting Tec2 to verify references (even start and end date, which is all some companies do, would presumably expose the lies)
* asking the same sort of questions you asked in the interview
You don't appear to have needed or relied on your relationship with Tec2 to discover this person is a fraud. Any company out there that does even minimal screening would make the same discovery. And any that doesn't (sure, they exist) would not be hooked into whatever mechanism or backchannel you're thinking of using to spread the word about an exaggerated, inflated, or even entirely fictional resume.
People do this. That's why interviewers check. And interviewers who check don't hire people who do this. You don't have a part to play in this beyond protecting your own agency from hiring or placing this person, which you did. | >
> Beyond simply declining to hire the candidate, does Acme have any
> further ethical responsibilities?
>
>
>
Besides not placing the candidate, I don't think there is anything further for you to do from an ethical or just plain ole professional point of view. You definitely **can not spread the word**, so to speak, about J. Doe being a bad candidate.
Something you **could** do is share the feedback you received with J. Doe in an attempt to help them grow or perhaps refine their resume. |
101,609 | Acme Co. screens and places candidates at other companies including those fictionally-named Bravo and Tec2.
Candidate J. Doe applies for a role with Bravo, including a resume citing a lot of experience on a project at Tec2.
Acme learns that this is a serious misrepresentation, through a combination of its own knowledge resulting from the partnership with Tec2 and J. Doe's performance on interview questions that should have been easy if the resume was truthful.
Beyond simply declining to hire the candidate, does Acme have any further ethical responsibilities? | 2017/10/27 | [
"https://workplace.stackexchange.com/questions/101609",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/37509/"
] | >
> Beyond simply declining to hire the candidate, does Acme have any
> further ethical responsibilities?
>
>
>
Besides not placing the candidate, I don't think there is anything further for you to do from an ethical or just plain ole professional point of view. You definitely **can not spread the word**, so to speak, about J. Doe being a bad candidate.
Something you **could** do is share the feedback you received with J. Doe in an attempt to help them grow or perhaps refine their resume. | From a **professional** perspective, doing anything more than weeding out the candidate of your own recruitment process would be unethical.
Reason is simple: The purpose of any for-profit company is to maximize its (financial) success. It is unethical to abuse it´s resources for other goals.
Volunteering Information to third parties takes your and their resources, and does not serve this goal from your perspective. Apart from that, it is possibly opening you up to all sorts of legal and data-protection issues the could pose a risk to your organisation.
*You are offering to volunteer a service nobody ordered and nobody pays for!*
Note: This answer would be different, if you where, for example, part of a network of entrepreneurs who mutually join forces to screen for bad candidates. |
101,609 | Acme Co. screens and places candidates at other companies including those fictionally-named Bravo and Tec2.
Candidate J. Doe applies for a role with Bravo, including a resume citing a lot of experience on a project at Tec2.
Acme learns that this is a serious misrepresentation, through a combination of its own knowledge resulting from the partnership with Tec2 and J. Doe's performance on interview questions that should have been easy if the resume was truthful.
Beyond simply declining to hire the candidate, does Acme have any further ethical responsibilities? | 2017/10/27 | [
"https://workplace.stackexchange.com/questions/101609",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/37509/"
] | Literally any employer could find this out by
* contacting Tec2 to verify references (even start and end date, which is all some companies do, would presumably expose the lies)
* asking the same sort of questions you asked in the interview
You don't appear to have needed or relied on your relationship with Tec2 to discover this person is a fraud. Any company out there that does even minimal screening would make the same discovery. And any that doesn't (sure, they exist) would not be hooked into whatever mechanism or backchannel you're thinking of using to spread the word about an exaggerated, inflated, or even entirely fictional resume.
People do this. That's why interviewers check. And interviewers who check don't hire people who do this. You don't have a part to play in this beyond protecting your own agency from hiring or placing this person, which you did. | >
> Beyond simply declining to hire the candidate, does Acme have any further ethical responsibilities?
>
>
>
None at all including hiring the chap despite the dodginess. Businesses do not have clear cut ethical responsibilities. They have legal obligations. |
101,609 | Acme Co. screens and places candidates at other companies including those fictionally-named Bravo and Tec2.
Candidate J. Doe applies for a role with Bravo, including a resume citing a lot of experience on a project at Tec2.
Acme learns that this is a serious misrepresentation, through a combination of its own knowledge resulting from the partnership with Tec2 and J. Doe's performance on interview questions that should have been easy if the resume was truthful.
Beyond simply declining to hire the candidate, does Acme have any further ethical responsibilities? | 2017/10/27 | [
"https://workplace.stackexchange.com/questions/101609",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/37509/"
] | Literally any employer could find this out by
* contacting Tec2 to verify references (even start and end date, which is all some companies do, would presumably expose the lies)
* asking the same sort of questions you asked in the interview
You don't appear to have needed or relied on your relationship with Tec2 to discover this person is a fraud. Any company out there that does even minimal screening would make the same discovery. And any that doesn't (sure, they exist) would not be hooked into whatever mechanism or backchannel you're thinking of using to spread the word about an exaggerated, inflated, or even entirely fictional resume.
People do this. That's why interviewers check. And interviewers who check don't hire people who do this. You don't have a part to play in this beyond protecting your own agency from hiring or placing this person, which you did. | I would say: it depends.
In general, you wouldn't hunt people with misrepresentation on their resume. That could even bounce back to you. And cost a lot of money in litigation.
However, if for instance the fraud is that someone claims he's a doctor and you find out that he isn't. And you later find out he's working somewhere else as a doctor. I would inform that company.
So my answer is: 90% of the times, just let it go, but there are situations where you actually have to. It depends on the actual fraud. |
101,609 | Acme Co. screens and places candidates at other companies including those fictionally-named Bravo and Tec2.
Candidate J. Doe applies for a role with Bravo, including a resume citing a lot of experience on a project at Tec2.
Acme learns that this is a serious misrepresentation, through a combination of its own knowledge resulting from the partnership with Tec2 and J. Doe's performance on interview questions that should have been easy if the resume was truthful.
Beyond simply declining to hire the candidate, does Acme have any further ethical responsibilities? | 2017/10/27 | [
"https://workplace.stackexchange.com/questions/101609",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/37509/"
] | Literally any employer could find this out by
* contacting Tec2 to verify references (even start and end date, which is all some companies do, would presumably expose the lies)
* asking the same sort of questions you asked in the interview
You don't appear to have needed or relied on your relationship with Tec2 to discover this person is a fraud. Any company out there that does even minimal screening would make the same discovery. And any that doesn't (sure, they exist) would not be hooked into whatever mechanism or backchannel you're thinking of using to spread the word about an exaggerated, inflated, or even entirely fictional resume.
People do this. That's why interviewers check. And interviewers who check don't hire people who do this. You don't have a part to play in this beyond protecting your own agency from hiring or placing this person, which you did. | From a **professional** perspective, doing anything more than weeding out the candidate of your own recruitment process would be unethical.
Reason is simple: The purpose of any for-profit company is to maximize its (financial) success. It is unethical to abuse it´s resources for other goals.
Volunteering Information to third parties takes your and their resources, and does not serve this goal from your perspective. Apart from that, it is possibly opening you up to all sorts of legal and data-protection issues the could pose a risk to your organisation.
*You are offering to volunteer a service nobody ordered and nobody pays for!*
Note: This answer would be different, if you where, for example, part of a network of entrepreneurs who mutually join forces to screen for bad candidates. |
101,609 | Acme Co. screens and places candidates at other companies including those fictionally-named Bravo and Tec2.
Candidate J. Doe applies for a role with Bravo, including a resume citing a lot of experience on a project at Tec2.
Acme learns that this is a serious misrepresentation, through a combination of its own knowledge resulting from the partnership with Tec2 and J. Doe's performance on interview questions that should have been easy if the resume was truthful.
Beyond simply declining to hire the candidate, does Acme have any further ethical responsibilities? | 2017/10/27 | [
"https://workplace.stackexchange.com/questions/101609",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/37509/"
] | >
> Beyond simply declining to hire the candidate, does Acme have any further ethical responsibilities?
>
>
>
None at all including hiring the chap despite the dodginess. Businesses do not have clear cut ethical responsibilities. They have legal obligations. | From a **professional** perspective, doing anything more than weeding out the candidate of your own recruitment process would be unethical.
Reason is simple: The purpose of any for-profit company is to maximize its (financial) success. It is unethical to abuse it´s resources for other goals.
Volunteering Information to third parties takes your and their resources, and does not serve this goal from your perspective. Apart from that, it is possibly opening you up to all sorts of legal and data-protection issues the could pose a risk to your organisation.
*You are offering to volunteer a service nobody ordered and nobody pays for!*
Note: This answer would be different, if you where, for example, part of a network of entrepreneurs who mutually join forces to screen for bad candidates. |
101,609 | Acme Co. screens and places candidates at other companies including those fictionally-named Bravo and Tec2.
Candidate J. Doe applies for a role with Bravo, including a resume citing a lot of experience on a project at Tec2.
Acme learns that this is a serious misrepresentation, through a combination of its own knowledge resulting from the partnership with Tec2 and J. Doe's performance on interview questions that should have been easy if the resume was truthful.
Beyond simply declining to hire the candidate, does Acme have any further ethical responsibilities? | 2017/10/27 | [
"https://workplace.stackexchange.com/questions/101609",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/37509/"
] | I would say: it depends.
In general, you wouldn't hunt people with misrepresentation on their resume. That could even bounce back to you. And cost a lot of money in litigation.
However, if for instance the fraud is that someone claims he's a doctor and you find out that he isn't. And you later find out he's working somewhere else as a doctor. I would inform that company.
So my answer is: 90% of the times, just let it go, but there are situations where you actually have to. It depends on the actual fraud. | From a **professional** perspective, doing anything more than weeding out the candidate of your own recruitment process would be unethical.
Reason is simple: The purpose of any for-profit company is to maximize its (financial) success. It is unethical to abuse it´s resources for other goals.
Volunteering Information to third parties takes your and their resources, and does not serve this goal from your perspective. Apart from that, it is possibly opening you up to all sorts of legal and data-protection issues the could pose a risk to your organisation.
*You are offering to volunteer a service nobody ordered and nobody pays for!*
Note: This answer would be different, if you where, for example, part of a network of entrepreneurs who mutually join forces to screen for bad candidates. |
6,750,884 | I have to write a program which requires to maintain some data in a directed flow graph. I need to compute the maximum-flow at runtime.
I know that there exist several libraries for handling graphs, implementing almost every classical algorithm, but my problem is that my graph is dynamic, meaning it evolves at runtime. After every evolution, I need to recompute the new maximum-flow.
An evolution is, either:
* adding an edge
* increasing the capacity of an edge
and what I need to re-compute is the maximum-flow from the source S to the destination node of the edge that has been modified at that step. For example:
```
S S
| |
5 5
| |
V V
A---3--->B A---5--->B
adding edge | | increasing | |
B-->D 2 1 A-->B of 2 1
| | two units | |
V V V V
C---3--->D C---3--->D
OUTPUT: 3 OUTPUT: 5
(maxflow S-D) (maxflow S-B)
```
Considering the very specific nature of the evolution in my graph, which algorithm/library would be more time-performant? I mean, considering the fact that at each step the graph is almost identical to the previous step (except for one edge), is there an algorithm that can efficiently re-use intermediate results of its previous computations?
I know that the fact that the destination is different every time makes the problem a bit hard.... any idea on how I can be better than O(VE^2) at each step?
And what if I also consider this possible evolution?
* deleting a node (and all the incoming/outgoing edges to/from that node)
I tried to understand all the standard algorithms and think how I could modify them, but being graph theory not exactly my field, I miserably failed...
Any help will be appreciated.
Thanks. | 2011/07/19 | [
"https://Stackoverflow.com/questions/6750884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852457/"
] | The only article I can find on the general case of this problem is [An Incremental Algorithm for the Maximum Flow Problem](https://doi.org/10.1023/A:1023607406540), by Kumar and Gupta. It's behind a paywall, but the main idea is pretty simple. When we increase the capacity of arc *uv*, traverse the graph twice to find all vertices *w* that lie on a path from *s* to *t* in the graph with arcs with positive residual capacity and *uv*. (Traverse backward from *u* and forward from *v*.) Starting with the previously computed flow, run Goldberg–Tarjan on these vertices.
To add an arc, first add it with capacity zero and then increase its capacity. Kumar–Gupta also considered decreasing capacity/removing arcs. This is more complicated; they push flow from *t* back to *v*, then delete *v*, then push flow forward again. | Do you have any libraries you are already working with? If I were you I'd at least search for one implementing the **network simplex**. |
394,606 | I want to reduce size `\bigcup_{n=1}^\infty`? How can I do it?
I tried `\newcommand*{\medcap}{\mathbin{\scalebox{0.75}{\ensuremath{\bigcap}}}` | 2017/10/04 | [
"https://tex.stackexchange.com/questions/394606",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/144920/"
] | You can probably simply use the smaller version available in the font:
[](https://i.stack.imgur.com/qku5O.png)
```
\documentclass{article}
\usepackage{amsmath}
\begin{document}
zzz
\[
\bigcup_0^n > {\textstyle \bigcup\limits_0^n} > \mathop{\cup}_0^n
\]
\end{document}
```
with the example added in comments I would keep the standard bigcup but use more reasonable brackets
[](https://i.stack.imgur.com/3B6UO.png)
```
\[\lambda\left(\bigcup_{j=1}^\infty E_k\right % no:-)
>
\lambda\Bigl(\bigcup_{j=1}^\infty E_k\Bigr)
\]
``` | Maybe you want the symbol to have the same size in display style as in text style. The thread you link is for growing the symbol *bigger*.
The argument to `\reduceoperator` should be a comma separated list of *names* of operators.
```
\documentclass{article}
\usepackage{amsmath}
\usepackage{etoolbox}
\makeatletter
\newcommand{\reduceoperator}[1]{%
\@for\next:=#1\do{\expandafter\reduceoperator@\expandafter{\next}}%
}
\newcommand{\reduceoperator@}[1]{%
\csletcs{normal@#1@}{#1@}%
\csedef{#1@}{\noexpand\reduceoperator@@\csname normal@#1@\endcsname}%
}
\newcommand{\reduceoperator@@}[1]{%
\mathop{\mathpalette\reduceoperator@@@{#1}}%
}
\newcommand{\reduceoperator@@@}[2]{%
\ifx#1\displaystyle\textstyle\fi#2%
}
\makeatother
\reduceoperator{bigcup,bigcap,bigotimes}
\begin{document}
\[
\bigcup_{i=1}^m\bigcap_{j=1}^n A_{ij}\bigotimes_{k=1}^uB_k
\]
\begin{center}% to test inline math
$\bigcup_{i=1}^m\bigcap_{j=1}^n A_{ij}$
\end{center}
\end{document}
```
[](https://i.stack.imgur.com/wE3AY.png) |
394,606 | I want to reduce size `\bigcup_{n=1}^\infty`? How can I do it?
I tried `\newcommand*{\medcap}{\mathbin{\scalebox{0.75}{\ensuremath{\bigcap}}}` | 2017/10/04 | [
"https://tex.stackexchange.com/questions/394606",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/144920/"
] | Maybe you want the symbol to have the same size in display style as in text style. The thread you link is for growing the symbol *bigger*.
The argument to `\reduceoperator` should be a comma separated list of *names* of operators.
```
\documentclass{article}
\usepackage{amsmath}
\usepackage{etoolbox}
\makeatletter
\newcommand{\reduceoperator}[1]{%
\@for\next:=#1\do{\expandafter\reduceoperator@\expandafter{\next}}%
}
\newcommand{\reduceoperator@}[1]{%
\csletcs{normal@#1@}{#1@}%
\csedef{#1@}{\noexpand\reduceoperator@@\csname normal@#1@\endcsname}%
}
\newcommand{\reduceoperator@@}[1]{%
\mathop{\mathpalette\reduceoperator@@@{#1}}%
}
\newcommand{\reduceoperator@@@}[2]{%
\ifx#1\displaystyle\textstyle\fi#2%
}
\makeatother
\reduceoperator{bigcup,bigcap,bigotimes}
\begin{document}
\[
\bigcup_{i=1}^m\bigcap_{j=1}^n A_{ij}\bigotimes_{k=1}^uB_k
\]
\begin{center}% to test inline math
$\bigcup_{i=1}^m\bigcap_{j=1}^n A_{ij}$
\end{center}
\end{document}
```
[](https://i.stack.imgur.com/wE3AY.png) | You can use the `\medmath` command from `nccmath` or `\mathsmaller` from `relsize`:
```
\documentclass[12pt]{article}
\usepackage[english]{babel}
\usepackage{mathtools, nccmath, relsize}
\begin{document}
\[ \bigcup_{n=1}^\infty A_n\qquad \medmath{\bigcup_{n=1}^\infty} A_n\qquad \mathsmaller{\bigcup\limits_{n=1}^\infty A_n}\]
\end{document}
```
[](https://i.stack.imgur.com/GMTWj.png) |
394,606 | I want to reduce size `\bigcup_{n=1}^\infty`? How can I do it?
I tried `\newcommand*{\medcap}{\mathbin{\scalebox{0.75}{\ensuremath{\bigcap}}}` | 2017/10/04 | [
"https://tex.stackexchange.com/questions/394606",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/144920/"
] | You can probably simply use the smaller version available in the font:
[](https://i.stack.imgur.com/qku5O.png)
```
\documentclass{article}
\usepackage{amsmath}
\begin{document}
zzz
\[
\bigcup_0^n > {\textstyle \bigcup\limits_0^n} > \mathop{\cup}_0^n
\]
\end{document}
```
with the example added in comments I would keep the standard bigcup but use more reasonable brackets
[](https://i.stack.imgur.com/3B6UO.png)
```
\[\lambda\left(\bigcup_{j=1}^\infty E_k\right % no:-)
>
\lambda\Bigl(\bigcup_{j=1}^\infty E_k\Bigr)
\]
``` | You can use the `\medmath` command from `nccmath` or `\mathsmaller` from `relsize`:
```
\documentclass[12pt]{article}
\usepackage[english]{babel}
\usepackage{mathtools, nccmath, relsize}
\begin{document}
\[ \bigcup_{n=1}^\infty A_n\qquad \medmath{\bigcup_{n=1}^\infty} A_n\qquad \mathsmaller{\bigcup\limits_{n=1}^\infty A_n}\]
\end{document}
```
[](https://i.stack.imgur.com/GMTWj.png) |
7,874,701 | I have 10 html which are stored in an array...I want to display each html by means of button click...But my app got crashed.. Here is the code..
```
int xpos=10,ypos=10;
for (int i=0; i<[array count]; i++) {
UIButton *but=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[but setTag:i];
but.backgroundColor=[UIColor redColor];
but.frame=CGRectMake(xpos, ypos, 50, 50);
xpos+=90;
[self.view addSubview:but];
[but addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
}
- (void)buttonClicked:(UIButton *)sender {
NSString *str=[array objectAtIndex:sender.tag];
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:str ofType:@"html"]isDirectory:NO]]];
[webview release];
}
```
How to overcome this problem? here is the crash report
24/10/11 4:56:08 PM Loading HTML[4655] **\* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '\*** -[NSURL initFileURLWithPath:isDirectory:]: nil string parameter' | 2011/10/24 | [
"https://Stackoverflow.com/questions/7874701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/870578/"
] | Where you are initializing the webview?
Please remove the `[webview release];` and try now. | ```
24/10/11 4:56:08 PM Loading HTML[4655] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSURL initFileURLWithPath:isDirectory:]: nil string parameter'
```
Your error log states that you are sending nil for the value **str**.
Please check the value of str. That should fix the problem. May be you have misspelled the name of the file.
---
**Update for comment**
Try replacing your file name there instead of getting it at run time.
```
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"yourHtmlFileNameGoesHere" ofType:@"html"]isDirectory:NO]]];
```
If the above works then you should be checking the array. |
7,874,701 | I have 10 html which are stored in an array...I want to display each html by means of button click...But my app got crashed.. Here is the code..
```
int xpos=10,ypos=10;
for (int i=0; i<[array count]; i++) {
UIButton *but=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[but setTag:i];
but.backgroundColor=[UIColor redColor];
but.frame=CGRectMake(xpos, ypos, 50, 50);
xpos+=90;
[self.view addSubview:but];
[but addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
}
- (void)buttonClicked:(UIButton *)sender {
NSString *str=[array objectAtIndex:sender.tag];
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:str ofType:@"html"]isDirectory:NO]]];
[webview release];
}
```
How to overcome this problem? here is the crash report
24/10/11 4:56:08 PM Loading HTML[4655] **\* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '\*** -[NSURL initFileURLWithPath:isDirectory:]: nil string parameter' | 2011/10/24 | [
"https://Stackoverflow.com/questions/7874701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/870578/"
] | Where you are initializing the webview?
Please remove the `[webview release];` and try now. | Looks like `[[NSBundle mainBundle] pathForResource:str ofType:@"html"]` results in nil - which means that the file could now be found in your main bundle. Make sure that file with that name and extension exists. Remember that file names are case sensitive. |
11,730,688 | Trying to get my head around some regex using JS .replace to replace an integer with a string.
For example, the string could be:
```
var string = 'image[testing][hello][0][welcome]';
```
I want to replace the '0' with another value. I was originally using this:
```
string.replace( /\[\d\]/g, '[newvalue]');
```
But when we start replacing double digits or more (12, 200, 3204, you get what I mean), it stops working properly. Not sure how to get it functioning the way I want it too.
Thanks in advance. Greatly appreciated. | 2012/07/30 | [
"https://Stackoverflow.com/questions/11730688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1067182/"
] | You need to specify multiple digits:
```
string.replace( /\[\d+\]/g, '[newvalue]');
```
[JS Fiddle demo](http://jsfiddle.net/davidThomas/6AMwJ/)
(Note the demo uses jQuery to iterate through the nodes, but it's merely a convenience, and has no bearing on the regular expression, it just demonstrates its function.)
The reason your original didn't work, I think, was because `\d` matches only a single digit, whereas the `+` operator/character specifies the preceding (in this case digit) character one or more times.
Reference:
* [JavaScript Regular Expressions, at the Mozilla Developer Network](https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions). | Use the following:
`string.replace( /\[\d+\]/g, '[newvalue]');`
That should match all digits in brackets. |
62,315,804 | I would like to hide some of these tables in my database. So i can make it look a little cleaner and simpler. i've been looking the web all over but cant find how. Does Anyone here know how can i do this? I've seen on youtube someone doing this but he never showed how he did it.
[](https://i.stack.imgur.com/FkHxv.png) | 2020/06/11 | [
"https://Stackoverflow.com/questions/62315804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11253378/"
] | You are currently using a design-time instance of `Charts`, which is generated by the designer. This instance is auto-generated and doesn't contain any data. This is the default behavior, which is controlled by the `IsDesignTimeCreatable` property of the markup extension `DesignInstanceExtension`. By default `IsDesignTimeCreatable` returns `false`, which directs the designer to create a fake instance using reflection (bypassing any constructor).
To use a design-time instance of the specified type which is properly constructed, you have to set this property explicitly to `true`:
```
<UserControl x:Class="KarateClub.Charts"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:KarateClub"
d:DataContext="{d:DesignInstance local:Charts, IsDesignTimeCreatable=True}" >
...
</UserControl>
```
Now the designer will create an instance using the constructor instead of using reflection.
Apparently this Blend design-time attributes are not well documented. To learn more see [Microsoft Docs: Design-Time Attributes in the Silverlight Designer](https://learn.microsoft.com/en-us/previous-versions/windows/silverlight/dotnet-windows-silverlight/ff602277%28v%3Dvs.95%29) | The example you are following does not say `d:DataContext="{d:DesignInstance local:Charts}"`.
it says `d:DataContext="{d:DesignInstance local:BasicColumn}"`. |
1,460,793 | I need to create a small app or script to install a .NET assembly into the GAC. I've read there are a couple ways to do this including:
* using `gacutil.exe`
* executing the following line of code:
`new System.EnterpriseServices.Internal.Publish().GACInstall("Foo.dll");`
However, what would happen if I just created the appropriate directories on the machine and copied the assembly into that directory? The structure of the GAC directory is the following: `C:\Windows\assembly\GAC_MSIL\Foo\<version#>__<public token>\Foo.dll`
Do the above two methods do anything special besides creating the folder structure and placing the assembly into it? | 2009/09/22 | [
"https://Stackoverflow.com/questions/1460793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177227/"
] | I *strongly* recommend using existing methods (like the ones you mentioned) because they are both supported and maintained by Microsoft and will continue to work with future releases.
A quick look at `gacutil.exe` with [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) reveals that there is a little bit more to it than just copying files:
* concurrency concerns (e.g. temporary files, locking `WINDOWS\assembly\GACLock.dat`, etc.)
* notifications (e.g. `HKLM\SOFTWARE\Microsoft\Fusion\GACChangeNotification\...`)
* indexing (e.g. `HKLM\SOFTWARE\Microsoft\Fusion\NativeImagesIndex...`)
* validation (e.g. strong name, ...)
The wrapper in `System.EnterpriseServices` is very similar to [this old blog post](http://blogs.msdn.com/junfeng/articles/229649.aspx) and should work just fine. | We recently had to do this for 10s of servers in an enterprise environment. We used Wix to build a very simple MSI (seriously - 5 minutes work) and published to all server (and dev boxes) through Group Policy. |
59,835,651 | I have a view in my storyboard. By default I have set the view height to "0". Based upon my condition I need to modify the height of view to a certain height and give greater than or equal to constraint. I have tried according to this link.
[Is there is a way to create constraint greater than or equal relation through code](https://stackoverflow.com/questions/44305834/is-there-is-a-way-to-create-constraint-greater-than-or-equal-relation-through-co).
But it is not working in my case. | 2020/01/21 | [
"https://Stackoverflow.com/questions/59835651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9804276/"
] | The best design solution for you would be to initialize member `obj` in the [initialization list](https://en.cppreference.com/w/cpp/language/initializer_list) like this:
```cpp
ClassA() : obj(someInt) { }
```
However, another option for you would be to declare the default constructor for `ClassB` like this:
```cpp
ClassB() {}
```
or simply let the compiler create the one for you by using this:
```cpp
ClassB() = default;
```
From C++ Standard this is:
>
> defaulted default constructor: the compiler will define the implicit
> default constructor even if other constructors are present.
>
>
>
If you go for a second option, then the following code would pass without the error:
```cpp
#include <iostream>
class ClassB {
public:
ClassB() = default;
ClassB(int i);
};
class ClassA {
ClassB obj;
public:
ClassA() {
int someInt = 0;
obj = ClassB(someInt);
}
};
int main() {
return 0;
}
```
Check it out [live](https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:2,endLineNumber:21,positionColumn:1,positionLineNumber:1,selectionStartColumn:2,selectionStartLineNumber:21,startColumn:1,startLineNumber:1),source:'%23include+%3Ciostream%3E%0A%0Aclass+ClassB+%7B%0Apublic:%0A++++ClassB()+%3D+default%3B%0A++++ClassB(int+i)%3B%0A%7D%3B%0A%0Aclass+ClassA+%7B%0A++++ClassB+obj%3B%0Apublic:+%0A++++ClassA()+%7B%0A++++++++int+someInt+%3D+0%3B%0A++++++++obj+%3D+ClassB(someInt)%3B%0A++++%7D%0A%7D%3B%0A%0Aint+main()+%7B%0A%0A++++return+0%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:54.308093994778076,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:clang900,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:1,lang:c%2B%2B,libs:!(),options:'-std%3Dc%2B%2B17',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'x86-64+clang+9.0.0+(Editor+%231,+Compiler+%231)+C%2B%2B',t:'0')),k:45.97651026222455,l:'4',m:51.042810098792536,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:1,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%231+with+x86-64+clang+9.0.0',t:'0')),header:(),l:'4',m:48.957189901207464,n:'0',o:'',s:0,t:'0')),k:45.691906005221924,l:'3',n:'0',o:'',t:'0')),l:'2',n:'0',o:'',t:'0')),version:4)
**Conclusion**
I would deeply recommend using the first option, the one with the initialization list because it is not needed to default construct objects before and then assigning to them. Also, this is the only option for objects that don't have an assignment operator.
**UPDATE 1**
One more way around this problem is using the `std::shared_ptr<ClassB> obj` in your `ClassA` as follows:
```cpp
#include <iostream>
#include <memory>
class ClassB {
public:
ClassB(int i);
};
class ClassA {
std::shared_ptr<ClassB> obj;
public:
ClassA() {
int someInt = 0;
obj = std::make_shared<ClassB>(someInt);
}
};
int main() {
return 0;
}
```
**UPDATE 2**
One more possibility that came up to my mind is to calculate integer in a separate function and the just call it as part of the initialization list like in the following code:
```cpp
#include <iostream>
class ClassB {
public:
ClassB(int i);
};
class ClassA {
ClassB obj;
public:
ClassA()
: obj(calculate())
{}
private:
int calculate() {
return 1;
}
};
int main() {
return 0;
}
```
Check it out [live](https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:14,j:1,lang:c%2B%2B,selection:(endColumn:2,endLineNumber:23,positionColumn:2,positionLineNumber:23,selectionStartColumn:2,selectionStartLineNumber:23,startColumn:2,startLineNumber:23),source:'%23include+%3Ciostream%3E%0A%0Aclass+ClassB+%7B%0Apublic:%0A++++ClassB(int+i)%3B%0A%7D%3B%0A%0Aclass+ClassA+%7B%0A++++ClassB+obj%3B%0Apublic:+%0A++++ClassA()%0A++++++++:+obj(calculate())%0A++++%7B%7D%0A%0Aprivate:%0A++++int+calculate()+%7B%0A++++++++return+1%3B%0A++++%7D%0A%7D%3B%0A%0Aint+main()+%7B%0A++++return+0%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:54.308093994778076,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((g:!((h:compiler,i:(compiler:g92,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'0',intel:'0',libraryCode:'1',trim:'1'),fontScale:14,j:1,lang:c%2B%2B,libs:!(),options:'--std%3Dc%2B%2B2a',selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1),l:'5',n:'0',o:'x86-64+gcc+9.2+(Editor+%231,+Compiler+%231)+C%2B%2B',t:'0')),k:45.97651026222455,l:'4',m:51.042810098792536,n:'0',o:'',s:0,t:'0'),(g:!((h:output,i:(compiler:1,editor:1,fontScale:14,wrap:'1'),l:'5',n:'0',o:'%231+with+x86-64+gcc+9.2',t:'0')),header:(),l:'4',m:48.957189901207464,n:'0',o:'',s:0,t:'0')),k:45.691906005221924,l:'3',n:'0',o:'',t:'0')),l:'2',n:'0',o:'',t:'0')),version:4) | You initialize members in the constructor initialization list. Like so:
```
ClassA() : obj(someInt) { }
``` |
965,977 | I have 2 objects to create that are identical except for that they refer to my dev and test WCF services. Basically, these are the object for the service itself, and the object for a DTO created by the WCF data-contract.
In my test client, I create either the 2 objects related to the dev WCF service, or the 2 objects related to the test WCF service. I then apply identical logic to both to test my service contract, etc.
What is the best way to structure this using OO principles, preferably without having to write the logic twice?
For reference, here are the objects I'm creating. The first set is from "ASRServiceClient". The second set comes from "ASRTestServiceClient".
```
ASRService.ASRServiceClient svc = new ASRService.ASRServiceClient();
ASRService.ASRItem tr1 = new ASRService.ASRItem();
``` | 2009/06/08 | [
"https://Stackoverflow.com/questions/965977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61639/"
] | Use an interface. | I would use an interface and have a setting in your config file that determines at run time what concrete class to create. |
965,977 | I have 2 objects to create that are identical except for that they refer to my dev and test WCF services. Basically, these are the object for the service itself, and the object for a DTO created by the WCF data-contract.
In my test client, I create either the 2 objects related to the dev WCF service, or the 2 objects related to the test WCF service. I then apply identical logic to both to test my service contract, etc.
What is the best way to structure this using OO principles, preferably without having to write the logic twice?
For reference, here are the objects I'm creating. The first set is from "ASRServiceClient". The second set comes from "ASRTestServiceClient".
```
ASRService.ASRServiceClient svc = new ASRService.ASRServiceClient();
ASRService.ASRItem tr1 = new ASRService.ASRItem();
``` | 2009/06/08 | [
"https://Stackoverflow.com/questions/965977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61639/"
] | Use an interface. | or maybe a [factory pattern](http://en.wikipedia.org/wiki/Factory_method_pattern) |
965,977 | I have 2 objects to create that are identical except for that they refer to my dev and test WCF services. Basically, these are the object for the service itself, and the object for a DTO created by the WCF data-contract.
In my test client, I create either the 2 objects related to the dev WCF service, or the 2 objects related to the test WCF service. I then apply identical logic to both to test my service contract, etc.
What is the best way to structure this using OO principles, preferably without having to write the logic twice?
For reference, here are the objects I'm creating. The first set is from "ASRServiceClient". The second set comes from "ASRTestServiceClient".
```
ASRService.ASRServiceClient svc = new ASRService.ASRServiceClient();
ASRService.ASRItem tr1 = new ASRService.ASRItem();
``` | 2009/06/08 | [
"https://Stackoverflow.com/questions/965977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61639/"
] | Why do you need to modify the code in your client based on which service you're connecting to? Wouldn't you just be able to have 2 different .config files? One that contains connection for dev service and one that contains connection for test service? Just switch out .config files based on test/dev mode.
Of course, the contract for your service would be an interface and both dev and test versions of the service use that same contract interface, but that didn't seem to be what you were asking.
**Edit:**
Extract a ServiceContract Interface for your service if you haven't already done so. Both your dev and test services should implement the interface. Something like this:
```
[ServiceContract(Namespace="http://stackoverflow.com/questions/965977")]
public interface IASRService
{
[OperationContract]
ASRItem GetASRItem();
}
```
Your app.config (or web.config) file for your client should contain something like this where `{namespace}` is the namespace location of your interface. If you wanted to keep them both in a single .config file, this will work.
```
<system.serviceModel>
<client>
<endpoint name="ASRService" address="http://yourserver.com/ASRService"
contract="{namespace}.IASRService" binding="basicHttpBinding"/>
<endpoint name="ASRServiceTest" address="http://localhost/ASRService"
contract="{namespace}.IASRService" binding="basicHttpBinding"/>
</client>
</system.serviceModel>
```
Code in your client that uses the services would look like this. Specify the name of the configuration in the ChannelFactory constructor.
```
ChannelFactory<IASRService> cf = new ChannelFactory<IASRService>("ASRService");
IASRService proxy = cf.CreateChannel();
ASRItem DevServiceItem = proxy.GetASRItem;
```
OR
```
ChannelFactory<IASRService> cfTest = new ChannelFactory<IASRService>("ASRServiceTest");
IASRService proxyTest = cfTest.CreateChannel();
ASRItem TestServiceItem = proxyTest.GetASRItem;
```
Since the type of either proxy is always IASRService, the code you have that manipulates the objects only needs to know about that Interface type. It shouldn't care which version of the service generated the object.
Also, I would recommend the book [Learning WCF](http://oreilly.com/catalog/9780596101626/) by Michele Leroux Bustamante. Great examples on how to do all this stuff! | Use an interface. |
965,977 | I have 2 objects to create that are identical except for that they refer to my dev and test WCF services. Basically, these are the object for the service itself, and the object for a DTO created by the WCF data-contract.
In my test client, I create either the 2 objects related to the dev WCF service, or the 2 objects related to the test WCF service. I then apply identical logic to both to test my service contract, etc.
What is the best way to structure this using OO principles, preferably without having to write the logic twice?
For reference, here are the objects I'm creating. The first set is from "ASRServiceClient". The second set comes from "ASRTestServiceClient".
```
ASRService.ASRServiceClient svc = new ASRService.ASRServiceClient();
ASRService.ASRItem tr1 = new ASRService.ASRItem();
``` | 2009/06/08 | [
"https://Stackoverflow.com/questions/965977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61639/"
] | Use an interface. | You could use a [Template method](http://en.wikipedia.org/wiki/Template_method_pattern), encapsulating the environment specific data for your services in subclasses.
However, this may not be a question of a pattern. It may be best to have environment-specific configuration files. |
965,977 | I have 2 objects to create that are identical except for that they refer to my dev and test WCF services. Basically, these are the object for the service itself, and the object for a DTO created by the WCF data-contract.
In my test client, I create either the 2 objects related to the dev WCF service, or the 2 objects related to the test WCF service. I then apply identical logic to both to test my service contract, etc.
What is the best way to structure this using OO principles, preferably without having to write the logic twice?
For reference, here are the objects I'm creating. The first set is from "ASRServiceClient". The second set comes from "ASRTestServiceClient".
```
ASRService.ASRServiceClient svc = new ASRService.ASRServiceClient();
ASRService.ASRItem tr1 = new ASRService.ASRItem();
``` | 2009/06/08 | [
"https://Stackoverflow.com/questions/965977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61639/"
] | Why do you need to modify the code in your client based on which service you're connecting to? Wouldn't you just be able to have 2 different .config files? One that contains connection for dev service and one that contains connection for test service? Just switch out .config files based on test/dev mode.
Of course, the contract for your service would be an interface and both dev and test versions of the service use that same contract interface, but that didn't seem to be what you were asking.
**Edit:**
Extract a ServiceContract Interface for your service if you haven't already done so. Both your dev and test services should implement the interface. Something like this:
```
[ServiceContract(Namespace="http://stackoverflow.com/questions/965977")]
public interface IASRService
{
[OperationContract]
ASRItem GetASRItem();
}
```
Your app.config (or web.config) file for your client should contain something like this where `{namespace}` is the namespace location of your interface. If you wanted to keep them both in a single .config file, this will work.
```
<system.serviceModel>
<client>
<endpoint name="ASRService" address="http://yourserver.com/ASRService"
contract="{namespace}.IASRService" binding="basicHttpBinding"/>
<endpoint name="ASRServiceTest" address="http://localhost/ASRService"
contract="{namespace}.IASRService" binding="basicHttpBinding"/>
</client>
</system.serviceModel>
```
Code in your client that uses the services would look like this. Specify the name of the configuration in the ChannelFactory constructor.
```
ChannelFactory<IASRService> cf = new ChannelFactory<IASRService>("ASRService");
IASRService proxy = cf.CreateChannel();
ASRItem DevServiceItem = proxy.GetASRItem;
```
OR
```
ChannelFactory<IASRService> cfTest = new ChannelFactory<IASRService>("ASRServiceTest");
IASRService proxyTest = cfTest.CreateChannel();
ASRItem TestServiceItem = proxyTest.GetASRItem;
```
Since the type of either proxy is always IASRService, the code you have that manipulates the objects only needs to know about that Interface type. It shouldn't care which version of the service generated the object.
Also, I would recommend the book [Learning WCF](http://oreilly.com/catalog/9780596101626/) by Michele Leroux Bustamante. Great examples on how to do all this stuff! | I would use an interface and have a setting in your config file that determines at run time what concrete class to create. |
965,977 | I have 2 objects to create that are identical except for that they refer to my dev and test WCF services. Basically, these are the object for the service itself, and the object for a DTO created by the WCF data-contract.
In my test client, I create either the 2 objects related to the dev WCF service, or the 2 objects related to the test WCF service. I then apply identical logic to both to test my service contract, etc.
What is the best way to structure this using OO principles, preferably without having to write the logic twice?
For reference, here are the objects I'm creating. The first set is from "ASRServiceClient". The second set comes from "ASRTestServiceClient".
```
ASRService.ASRServiceClient svc = new ASRService.ASRServiceClient();
ASRService.ASRItem tr1 = new ASRService.ASRItem();
``` | 2009/06/08 | [
"https://Stackoverflow.com/questions/965977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61639/"
] | Why do you need to modify the code in your client based on which service you're connecting to? Wouldn't you just be able to have 2 different .config files? One that contains connection for dev service and one that contains connection for test service? Just switch out .config files based on test/dev mode.
Of course, the contract for your service would be an interface and both dev and test versions of the service use that same contract interface, but that didn't seem to be what you were asking.
**Edit:**
Extract a ServiceContract Interface for your service if you haven't already done so. Both your dev and test services should implement the interface. Something like this:
```
[ServiceContract(Namespace="http://stackoverflow.com/questions/965977")]
public interface IASRService
{
[OperationContract]
ASRItem GetASRItem();
}
```
Your app.config (or web.config) file for your client should contain something like this where `{namespace}` is the namespace location of your interface. If you wanted to keep them both in a single .config file, this will work.
```
<system.serviceModel>
<client>
<endpoint name="ASRService" address="http://yourserver.com/ASRService"
contract="{namespace}.IASRService" binding="basicHttpBinding"/>
<endpoint name="ASRServiceTest" address="http://localhost/ASRService"
contract="{namespace}.IASRService" binding="basicHttpBinding"/>
</client>
</system.serviceModel>
```
Code in your client that uses the services would look like this. Specify the name of the configuration in the ChannelFactory constructor.
```
ChannelFactory<IASRService> cf = new ChannelFactory<IASRService>("ASRService");
IASRService proxy = cf.CreateChannel();
ASRItem DevServiceItem = proxy.GetASRItem;
```
OR
```
ChannelFactory<IASRService> cfTest = new ChannelFactory<IASRService>("ASRServiceTest");
IASRService proxyTest = cfTest.CreateChannel();
ASRItem TestServiceItem = proxyTest.GetASRItem;
```
Since the type of either proxy is always IASRService, the code you have that manipulates the objects only needs to know about that Interface type. It shouldn't care which version of the service generated the object.
Also, I would recommend the book [Learning WCF](http://oreilly.com/catalog/9780596101626/) by Michele Leroux Bustamante. Great examples on how to do all this stuff! | or maybe a [factory pattern](http://en.wikipedia.org/wiki/Factory_method_pattern) |
965,977 | I have 2 objects to create that are identical except for that they refer to my dev and test WCF services. Basically, these are the object for the service itself, and the object for a DTO created by the WCF data-contract.
In my test client, I create either the 2 objects related to the dev WCF service, or the 2 objects related to the test WCF service. I then apply identical logic to both to test my service contract, etc.
What is the best way to structure this using OO principles, preferably without having to write the logic twice?
For reference, here are the objects I'm creating. The first set is from "ASRServiceClient". The second set comes from "ASRTestServiceClient".
```
ASRService.ASRServiceClient svc = new ASRService.ASRServiceClient();
ASRService.ASRItem tr1 = new ASRService.ASRItem();
``` | 2009/06/08 | [
"https://Stackoverflow.com/questions/965977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61639/"
] | Why do you need to modify the code in your client based on which service you're connecting to? Wouldn't you just be able to have 2 different .config files? One that contains connection for dev service and one that contains connection for test service? Just switch out .config files based on test/dev mode.
Of course, the contract for your service would be an interface and both dev and test versions of the service use that same contract interface, but that didn't seem to be what you were asking.
**Edit:**
Extract a ServiceContract Interface for your service if you haven't already done so. Both your dev and test services should implement the interface. Something like this:
```
[ServiceContract(Namespace="http://stackoverflow.com/questions/965977")]
public interface IASRService
{
[OperationContract]
ASRItem GetASRItem();
}
```
Your app.config (or web.config) file for your client should contain something like this where `{namespace}` is the namespace location of your interface. If you wanted to keep them both in a single .config file, this will work.
```
<system.serviceModel>
<client>
<endpoint name="ASRService" address="http://yourserver.com/ASRService"
contract="{namespace}.IASRService" binding="basicHttpBinding"/>
<endpoint name="ASRServiceTest" address="http://localhost/ASRService"
contract="{namespace}.IASRService" binding="basicHttpBinding"/>
</client>
</system.serviceModel>
```
Code in your client that uses the services would look like this. Specify the name of the configuration in the ChannelFactory constructor.
```
ChannelFactory<IASRService> cf = new ChannelFactory<IASRService>("ASRService");
IASRService proxy = cf.CreateChannel();
ASRItem DevServiceItem = proxy.GetASRItem;
```
OR
```
ChannelFactory<IASRService> cfTest = new ChannelFactory<IASRService>("ASRServiceTest");
IASRService proxyTest = cfTest.CreateChannel();
ASRItem TestServiceItem = proxyTest.GetASRItem;
```
Since the type of either proxy is always IASRService, the code you have that manipulates the objects only needs to know about that Interface type. It shouldn't care which version of the service generated the object.
Also, I would recommend the book [Learning WCF](http://oreilly.com/catalog/9780596101626/) by Michele Leroux Bustamante. Great examples on how to do all this stuff! | You could use a [Template method](http://en.wikipedia.org/wiki/Template_method_pattern), encapsulating the environment specific data for your services in subclasses.
However, this may not be a question of a pattern. It may be best to have environment-specific configuration files. |
66,247,439 | Given this first dataframe `df_1`:
```
df_1 = pd.DataFrame({'id':[1,2,1,3,1],
'symbol':['A','B','C','A','A'],
'date':['2021-02-12','2021-02-09','2021-02-14','2021-02-02','2021-02-05'],
'value':[1,1,1,1,1]})
```
```
id symbol date value
0 1 A 2021-02-12 1
1 2 B 2021-02-09 1
2 1 C 2021-02-14 1
3 3 A 2021-02-02 1
4 1 A 2021-02-05 1
```
And given this second `df_2`:
```
df_2 = pd.DataFrame({'id_symbol':['1_A', '1_A'],
'init_date':['2021-02-01','2021-02-01'],
'end_date':['2021-02-05', '2021-02-12'],
'multiplier':[5,2]})
```
I need to apply this `df_2.multiplier` on `df_1` for rows on `df_1.value` where the concat of `id` and `_` and `symbol` is equals the `df_2.id_symbol`, and if the `df_1.date` is within the `df_2.init_date` and `df_2.end_date`.
My result should be like this, after the code:
```
id symbol date value
0 1 A 2021-02-12 2
1 2 B 2021-02-09 1
2 1 C 2021-02-14 1
3 3 A 2021-02-02 1
4 1 A 2021-02-05 10
```
5 = 1 \* 5 // 10 = 1 \* 5 \* 2
My both dataframes are quite bigger than this. | 2021/02/17 | [
"https://Stackoverflow.com/questions/66247439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7669782/"
] | Your `AlbumArt` struct definition is internal to the `ContentView` struct, so it is out of scope from the perspective of `PlayerView`. You might as well do the same for SongCell as well, you don't have to define it inside the `ContentView` struct.
If you move that `struct` definition to the root level of your swift file, it will compile.
```swift
struct ContentView: View {
// all your ContentView stuff
}
struct AlbumArt : View {
// this definition here
}
``` | I think I see you problem - you have placeholder code in your AlbumArt class:
`/*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/`
It appears in this part of your code:
```
if isWithText == true {
ZStack {
Blur(style: .dark)
Text(album.name).foregroundColor(.white)
}.frame(height: 60, alignment: .center) <--- RIGHT HERE
}
```
Let me know if that fixes it! |
20,202,815 | Is there a way to execute a stored procedure every time a database is queried? I'm running SQL Server 2012
I want to be able to do something like the following:
I have database MyDB containing tables Table1 and Table2.
I've deprecated Table1, and now every time someone runs any select statement against Table1 (e.g. `SELECT * FROM Table1`) I want to call a certain stored procedure that will log a message saying Table1 was accessed, so that I know some code is still accessing an old table and can go and remove that dependency.
Is this possible? | 2013/11/25 | [
"https://Stackoverflow.com/questions/20202815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21539/"
] | When I want to do something similar to what you are talking-about, I have used a View. (eg. Rename the table from dbo.Table1 to dbo.Table1\_Orig and create a View like dbo.Table1, which is a wrapper around the table and includes a SP call or inline-function or equiv). Views can behave like a table and often seem transparent to a user/app.
Otherwise, if your server is not really busy, you might want to consider using the SQL profiler, with a filter for that specific table, so it doesn't record gigs of queries. It will add some overhead onto a server (5%) but otherwise, it is pretty unobtrusive and easy to turn on/off. Some people are really wary of leaving Profiler on for very long, and some companies forbid pointing Profiler at a production DB. So be really careful if you try it. Keep an eye on it. You probably don't want to just leave it running for a few months. That would be evil. | I can think of one way to do what you want, but its pretty nasty, so as an alternative:
I'm assuming however that Table2 is effectively a replacement for Table1?
In which case, would it be possible to simply drop Table1 and replace it with a view of the same name that transforms Table2 into the shape of the original Table1?
That way, you wouldn't need to log a message, since any code you have missed will effectively be accessing the correct table by virtue of the view...
If that is no good for you, then here is my pretty hacky answer. It relies on you enabling xp\_cmdshell, and uses that as a hack to get around functions not being allowed side effects:
1) Enable xp\_cmdshell:
```
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
```
2) Rename Table1 to something else, say Deprecated\_Table1
3) Create a function that returns the data from Table1, and also logs a message to your log:
```
CREATE FUNCTION GetTable1()
RETURNS @Table1 TABLE
(
ID int
)
AS
BEGIN
DECLARE @sql varchar(3000)
DECLARE @cmd varchar(4000)
SELECT @sql = 'INSERT INTO MyLog Values(''Oops a daisy'')'
SELECT @cmd = 'sqlcmd -S ' + @@servername + ' -d ' + db_name() + ' -Q "' + @sql + '"'
EXEC master..xp_cmdshell @cmd, 'no_output'
INSERT INTO @Table1
SELECT ID FROM Deprecated_Table1
RETURN
END
```
4) Create a view called Table1 that your legacy code will access, that calls the above function, and thus logs a message:
```
CREATE VIEW Table1 AS SELECT * FROM GetTable1()
```
Its deeply horrible, but since I guess this is just a temporary measure while you find all of the code you've missed, maybe it'll help you... |
71,615,947 | ```
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Range("M1:N1").Columns(1).Value = "ΕΜΒΑΣΜΑ" Then
Columns("U").EntireColumn.Hidden = False
Columns("V").EntireColumn.Hidden = False
Else
Columns("U").EntireColumn.Hidden = True
Columns("V").EntireColumn.Hidden = True
End If
End Sub
```
So I have been having trouble with this code here. What I want to do is hide U, V columns if there is a value in M column called "ΕΜΒΑΣΜΑ".
Every time I let it run, it automatically hides the columns even if I have the value already in my column. Other than that, it doesn't seem to work in real time so even if I change anything, nothing happens.
Any ideas? | 2022/03/25 | [
"https://Stackoverflow.com/questions/71615947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7169230/"
] | **(a)** If you want to check a whole column, you need to specify the whole column, e.g. with Range("M:M").
**(b)** You can't compare a Range that contains more than one cell with a value. `If Range("M:M").Columns(1).Value = "ΕΜΒΑΣΜΑ" Then` will throw a Type mismatch error (13). That is because a Range containing more that cell will be converted into a 2-dimensional array and you can't compare an array with a single value.
One way to check if a column contains a specific value is with the `CountIf`-function:
```
If WorksheetFunction.CountIf(Range("M:M"), "ΕΜΒΑΣΜΑ") > 0 Then
```
To shorten your code, you could use
```
Dim hideColumns As Boolean
hideColumns = (WorksheetFunction.CountIf(Range("M:M"), "ΕΜΒΑΣΜΑ") = 0)
Columns("U:V").EntireColumn.Hidden = hideColumns
```
**Update**
If you want to use that code in other events than a worksheet event, you should specify on which worksheet you want to work. Put the following routine in a regular module:
```
Sub showHideColumns(ws as Worksheet)
Dim hideColumns As Boolean
hideColumns = (WorksheetFunction.CountIf(ws.Range("M:M"), "ΕΜΒΑΣΜΑ") = 0)
ws.Columns("U:V").EntireColumn.Hidden = hideColumns
End Sub
```
Now all you have to do is to call that routine whenever you want and pass the worksheet as parameter. This could be the Workbook.Open - Event, or the click event of a button or shape. Eg put the following code in the Workbook module:
```
Private Sub Workbook_Open()
showHideColumns ThisWorkbook.Sheets(1)
End Sub
``` | on a fast hand I would go like this...
maybe someone can do it shorter...
```
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim sht As Worksheet: Set sht = ActiveSheet
Dim c As Range
With sht.Range("M1:M" & sht.Cells(sht.Rows.Count, "M").End(xlUp).Row)
Set c = .Find("XXX", LookIn:=xlValues)
If Not c Is Nothing Then
Columns("U:V").EntireColumn.Hidden = True
Else
Columns("U:V").EntireColumn.Hidden = False
End If
End With
End Sub
``` |
41,182 | I am reading the article "K-Theory and Elliptic Operators"(http://arxiv.org/abs/math/0504555), which is about Atiyah-Singer index theorem. In page 14 the article discussed the Thom isomorphism: $$\psi:H^{k}(X)\rightarrow H^{n+k}\_{c}(E)$$ and $$\phi:K(X)\rightarrow K(E)$$ with $\psi: x \rightarrow \pi^{\*}x\* \lambda\_{E}$ and $\phi:x \rightarrow \pi^{\*}x\cup \mu$. Greg further defined a correction factor $\mu(E)$ such that $$\psi(\mu(E)\cup \operatorname{ch}(x))=\operatorname{ch}(\phi(x))$$ He analyzed $\mu(E)$ by splitting principle and give the expression $$\mu(E)\cup e(E\_{\mathbb{R}})=\operatorname{ch}\left(\sum^{n}\_{i=0}(-1)^{i}\wedge^{i}(E)\right)=\operatorname{ch}\left(\prod^{n}\_{i=1}(1-L\_{i})\right)=\prod^{n}\_{i=1}(1-e^{x\_{i}})$$
He argued that since $e(E\_{\mathbb{R}})=c\_{n}E=\prod x\_{i}$ we can conclude $$\mu(E)=\prod^{n}\_{i=1} \frac{1-e^{x\_{i}}}{x\_{i}}$$ He then define the Todd class $$\operatorname{td}(E)=\prod^{n}\_{i=1}\frac{x\_{i}}{1-e^{-x\_{i}}}$$ such that we have $$\mu(E)=(-1)^{n}\operatorname{td}(\overline{E})^{-1}$$
My questions are:
1. Is the step from $\mu(E)\cup e(E\_{\mathbb{R}})$ to $\mu(E)$ justified? I feel uncertain about this as I have only seen it somewhere in Milnor & Stasheff's appendix, I do not know if this is the cap product or some other operation. Normally cup product made $H^{\*}\_{c}(E)$ to be a ring instead of a field. I think I need to clarify details in here.
2. Why we define the Todd class in terms of the relationship $$\operatorname{td}(E)=\prod^{n}\_{i=1}\frac{x\_{i}}{1-e^{-x\_{i}}}$$ instead of just using the result for $\mu(E)$? Is there any deeper motivation for it? On the other hand, why cannot we simply define $\mu(E)$ by the relation $\mu(E)\cup \psi(\operatorname{ch}(x))=\operatorname{ch}(\phi(x))$? I am not sure what the calculation of this will be but I feel it should be easier than the calculation in previous definition.
I did take a look at the wikipedia article and found the two definitions are mostly the same. I think maybe with time I can understand Todd class better. It is not mentioned in the book *Characteristic classes* (at least the part I covered) so I feel I do not really understand it (I hope I can understand it enough to understand the Atiyah-Singer index theorem). | 2011/05/25 | [
"https://math.stackexchange.com/questions/41182",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/7887/"
] | ### (Re: 2)
AFAIK, the Todd class is slightly more convenient (than $\mu$) in various forms of (Grothendieck-Hirzebruch-)Riemann-Roch theorem. For example, if $f\colon X\to Y$ is a map of (compact stably almost complex) manifolds, the diagram
$$\begin{array}{ccc}
K(X) & \stackrel{ch}{\longrightarrow} & H(X;\mathbb Q)\\
\downarrow{f\_\*} && \downarrow{f\_\*}\\
K(Y) & \stackrel{ch}{\longrightarrow} & H(Y;\mathbb Q)
\end{array}$$
is *not* commutative, but the diagram
$$\begin{array}{ccc}
K(X) & \stackrel{td(X)\cdot ch}{\longrightarrow} & H(X;\mathbb Q)\\
\downarrow{f\_\*} && \downarrow{f\_\*}\\
K(Y) & \stackrel{td(Y)\cdot ch}{\longrightarrow} & H(Y;\mathbb Q)
\end{array}$$
is.
---
By the way, it also explains the role, the Todd class plays in the Atiyah-Singer index theorem: $\int\_M ch([\sigma(D)])\cdot td(M)$ of the RHS is nothing else but $\int\_M[\sigma(D)]$ (where $\int\_M$ is the direct image under the projection $M\to pt$ in cohomology/K-theory), so Atiyah-Singer boils down to just $\operatorname{ind} D=\int\_M[\sigma(D)]$ (of course, when one actually tries to apply A-S, the traditional form is more convenient). | I just wish to answer that a nice source regarding this can be found in here:
<https://mathoverflow.net/questions/60478/hirzebruchs-motivation-of-the-todd-class/60481#60481>
very ashramed that did not found this before. |
28,148,125 | I want to use the bootstrap-datepicker (<https://bootstrap-datepicker.readthedocs.org>) in my django application. I use Django 1.7.
In index.html file I have:
```
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap-theme.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/js/bootstrap-datepicker.js' %}">
<link rel="stylesheet" href="{% static 'my_app/css/datepicker.css' %}">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
```
In my forms.py I have:
```
class Filter(django_filters.FilterSet):
class Meta:
model = MyModel
fields = ['user', 'date_from', 'date_to']
widgets = {'date': forms.DateInput(attrs={'class':'datepicker'})}
```
I my model.py I use to set date:
```
date_from = models.DateField()
date_to = models.DateField()
```
When I'm going through the page with the date - does not work in input area. | 2015/01/26 | [
"https://Stackoverflow.com/questions/28148125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2962768/"
] | I went through similar issue. You need to call the jquery min file before any custom jquery files. so your code would look like this.
```
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap-theme.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/datepicker.css' %}">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="{% static 'my_app/js/bootstrap-datepicker.js' %}">
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
```
I know this hasn't been answered in a few months but wanted to post this just to make sure this might help any one else. | While there is a python package that seems to solve this quite well I chose to see if I could make the datepicker work using Django's [widget](https://docs.djangoproject.com/en/1.9/ref/forms/widgets/#widget) class to render datepicker attributes, mentioned in the [docs](https://eonasdan.github.io/bootstrap-datetimepicker/).
**Note, I am only using a date field and not a date time field because I do not need my app to support times in this instance.**
**models.py**
```
class MyModel(models.Model):
...
date = models.DateField()
...
```
**forms.py**
```
class MyForm(forms.Form):
...
'''
Here I create a dict of the HTML attributes
I want to pass to the template.
'''
DATEPICKER = {
'type': 'text',
'class': 'form-control',
'id': 'datetimepicker4'
}
# Call attrs with form widget
date = forms.DateField(widget=forms.DateInput(attrs=DATEPICKER))
...
```
**template.html**
```
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
{{ form.date }}
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
```
**JS**
```
$(function () {
$('#datetimepicker1').datetimepicker({
format: 'YYYY-MM-DD' //This is the default date format Django will accept, it also disables the time in the datepicker.
})
});
``` |
28,148,125 | I want to use the bootstrap-datepicker (<https://bootstrap-datepicker.readthedocs.org>) in my django application. I use Django 1.7.
In index.html file I have:
```
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap-theme.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/js/bootstrap-datepicker.js' %}">
<link rel="stylesheet" href="{% static 'my_app/css/datepicker.css' %}">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
```
In my forms.py I have:
```
class Filter(django_filters.FilterSet):
class Meta:
model = MyModel
fields = ['user', 'date_from', 'date_to']
widgets = {'date': forms.DateInput(attrs={'class':'datepicker'})}
```
I my model.py I use to set date:
```
date_from = models.DateField()
date_to = models.DateField()
```
When I'm going through the page with the date - does not work in input area. | 2015/01/26 | [
"https://Stackoverflow.com/questions/28148125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2962768/"
] | **Update: Warning, this suggestion uses the dateTIMEpicker instead of datepicker. I suggested this because you don't have to use the time functionality of the datetimepicker, so it was quite handy in my case.**
Since I have been trying to get datetimepicker to work (in combination with a model form) for quite some time, I thought I would post the solution, that feels like an accumulation of all stackoverflow posts on this topic ;)
So, first of all, make sure to also include **[moment.js](http://momentjs.com/)**, as it is required by bootstrap-datetimepicker (see [this stackoverflow post](https://stackoverflow.com/a/21459914/5353710)). The order is important, see the mentioned post.
Then use [this site](https://eonasdan.github.io/bootstrap-datetimepicker/) to get the type of datetimepicker you need. If you have no model form in which you want to embed the datetimepicker, you should be fine with just copying that into your html code.
If you want to make one of your model forms field a fancy datepicker (without time) field like I did, then do the following:
**base.html**
```
<script type="text/javascript" src="scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="scripts/moment-2.4.0.js"></script>
<script type="text/javascript" src="scripts/bootstrap-datetimepicker.js"></script>
```
**forms.py**
```
class MyForm(forms.ModelForm):
class Meta:
...
widgets = {'myDateField': forms.DateInput(attrs={'id': 'datetimepicker12'})}
...
```
**myForm.html:**
```
<div class="row">
...
{% bootstrap_form form %}
...
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker12').datetimepicker({
inline: true,
sideBySide: true,
format: 'DD.MM.YYYY' /*remove this line if you want to use time as well */
});
});
</script>
```
I hope I was able to save you some time :) | I went through similar issue. You need to call the jquery min file before any custom jquery files. so your code would look like this.
```
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap-theme.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/datepicker.css' %}">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="{% static 'my_app/js/bootstrap-datepicker.js' %}">
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
```
I know this hasn't been answered in a few months but wanted to post this just to make sure this might help any one else. |
28,148,125 | I want to use the bootstrap-datepicker (<https://bootstrap-datepicker.readthedocs.org>) in my django application. I use Django 1.7.
In index.html file I have:
```
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap-theme.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/js/bootstrap-datepicker.js' %}">
<link rel="stylesheet" href="{% static 'my_app/css/datepicker.css' %}">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
```
In my forms.py I have:
```
class Filter(django_filters.FilterSet):
class Meta:
model = MyModel
fields = ['user', 'date_from', 'date_to']
widgets = {'date': forms.DateInput(attrs={'class':'datepicker'})}
```
I my model.py I use to set date:
```
date_from = models.DateField()
date_to = models.DateField()
```
When I'm going through the page with the date - does not work in input area. | 2015/01/26 | [
"https://Stackoverflow.com/questions/28148125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2962768/"
] | **Update: Warning, this suggestion uses the dateTIMEpicker instead of datepicker. I suggested this because you don't have to use the time functionality of the datetimepicker, so it was quite handy in my case.**
Since I have been trying to get datetimepicker to work (in combination with a model form) for quite some time, I thought I would post the solution, that feels like an accumulation of all stackoverflow posts on this topic ;)
So, first of all, make sure to also include **[moment.js](http://momentjs.com/)**, as it is required by bootstrap-datetimepicker (see [this stackoverflow post](https://stackoverflow.com/a/21459914/5353710)). The order is important, see the mentioned post.
Then use [this site](https://eonasdan.github.io/bootstrap-datetimepicker/) to get the type of datetimepicker you need. If you have no model form in which you want to embed the datetimepicker, you should be fine with just copying that into your html code.
If you want to make one of your model forms field a fancy datepicker (without time) field like I did, then do the following:
**base.html**
```
<script type="text/javascript" src="scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="scripts/moment-2.4.0.js"></script>
<script type="text/javascript" src="scripts/bootstrap-datetimepicker.js"></script>
```
**forms.py**
```
class MyForm(forms.ModelForm):
class Meta:
...
widgets = {'myDateField': forms.DateInput(attrs={'id': 'datetimepicker12'})}
...
```
**myForm.html:**
```
<div class="row">
...
{% bootstrap_form form %}
...
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker12').datetimepicker({
inline: true,
sideBySide: true,
format: 'DD.MM.YYYY' /*remove this line if you want to use time as well */
});
});
</script>
```
I hope I was able to save you some time :) | While there is a python package that seems to solve this quite well I chose to see if I could make the datepicker work using Django's [widget](https://docs.djangoproject.com/en/1.9/ref/forms/widgets/#widget) class to render datepicker attributes, mentioned in the [docs](https://eonasdan.github.io/bootstrap-datetimepicker/).
**Note, I am only using a date field and not a date time field because I do not need my app to support times in this instance.**
**models.py**
```
class MyModel(models.Model):
...
date = models.DateField()
...
```
**forms.py**
```
class MyForm(forms.Form):
...
'''
Here I create a dict of the HTML attributes
I want to pass to the template.
'''
DATEPICKER = {
'type': 'text',
'class': 'form-control',
'id': 'datetimepicker4'
}
# Call attrs with form widget
date = forms.DateField(widget=forms.DateInput(attrs=DATEPICKER))
...
```
**template.html**
```
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
{{ form.date }}
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
```
**JS**
```
$(function () {
$('#datetimepicker1').datetimepicker({
format: 'YYYY-MM-DD' //This is the default date format Django will accept, it also disables the time in the datepicker.
})
});
``` |
28,148,125 | I want to use the bootstrap-datepicker (<https://bootstrap-datepicker.readthedocs.org>) in my django application. I use Django 1.7.
In index.html file I have:
```
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap-theme.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/js/bootstrap-datepicker.js' %}">
<link rel="stylesheet" href="{% static 'my_app/css/datepicker.css' %}">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
```
In my forms.py I have:
```
class Filter(django_filters.FilterSet):
class Meta:
model = MyModel
fields = ['user', 'date_from', 'date_to']
widgets = {'date': forms.DateInput(attrs={'class':'datepicker'})}
```
I my model.py I use to set date:
```
date_from = models.DateField()
date_to = models.DateField()
```
When I'm going through the page with the date - does not work in input area. | 2015/01/26 | [
"https://Stackoverflow.com/questions/28148125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2962768/"
] | **For DJango version 2.1, 2.0, 1.11, 1.10 and 1.8**
To use Bootstrap date-picker in your Django app install [django-bootstrap-datepicker-plus](https://github.com/monim67/django-bootstrap-datepicker-plus), follow the [installation instructions](https://github.com/monim67/django-bootstrap-datepicker-plus#installing) on the GitHub page to configure it, then you can use it in Custom Forms and Model Forms as below.
**Usage in Custom Forms:**
```
from bootstrap_datepicker_plus import DatePickerInput
class ToDoForm(forms.Form):
user = forms.CharField()
date_from = forms.DateField(widget = DatePickerInput())
```
**Usage in Model Forms**:
```
from bootstrap_datepicker_plus import DatePickerInput
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['user', 'date_from', 'date_to']
widgets = {
'date_form': DatePickerInput(),
'date_to': DatePickerInput()
}
```
**Usage with django-filters:**
```
from bootstrap_datepicker_plus import DatePickerInput
class Filter(django_filters.FilterSet):
class Meta:
model = MyModel
fields = ['user', 'date_from', 'date_to']
widgets = {'date': DatePickerInput()}
```
**Disclaimer:** *This django package is maintained by me. For any issues with it please [open issues](https://github.com/monim67/django-bootstrap-datepicker-plus/issues/new) on the Github Page instead of putting comments here.* | While there is a python package that seems to solve this quite well I chose to see if I could make the datepicker work using Django's [widget](https://docs.djangoproject.com/en/1.9/ref/forms/widgets/#widget) class to render datepicker attributes, mentioned in the [docs](https://eonasdan.github.io/bootstrap-datetimepicker/).
**Note, I am only using a date field and not a date time field because I do not need my app to support times in this instance.**
**models.py**
```
class MyModel(models.Model):
...
date = models.DateField()
...
```
**forms.py**
```
class MyForm(forms.Form):
...
'''
Here I create a dict of the HTML attributes
I want to pass to the template.
'''
DATEPICKER = {
'type': 'text',
'class': 'form-control',
'id': 'datetimepicker4'
}
# Call attrs with form widget
date = forms.DateField(widget=forms.DateInput(attrs=DATEPICKER))
...
```
**template.html**
```
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
{{ form.date }}
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
```
**JS**
```
$(function () {
$('#datetimepicker1').datetimepicker({
format: 'YYYY-MM-DD' //This is the default date format Django will accept, it also disables the time in the datepicker.
})
});
``` |
28,148,125 | I want to use the bootstrap-datepicker (<https://bootstrap-datepicker.readthedocs.org>) in my django application. I use Django 1.7.
In index.html file I have:
```
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap-theme.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/js/bootstrap-datepicker.js' %}">
<link rel="stylesheet" href="{% static 'my_app/css/datepicker.css' %}">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
```
In my forms.py I have:
```
class Filter(django_filters.FilterSet):
class Meta:
model = MyModel
fields = ['user', 'date_from', 'date_to']
widgets = {'date': forms.DateInput(attrs={'class':'datepicker'})}
```
I my model.py I use to set date:
```
date_from = models.DateField()
date_to = models.DateField()
```
When I'm going through the page with the date - does not work in input area. | 2015/01/26 | [
"https://Stackoverflow.com/questions/28148125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2962768/"
] | (*Django 2.1, 1.11* and python >*2.7* and > *3.4* compatible) Working and **reusable** solution, custom from [bootstrap-datepicker](https://bootstrap-datepicker.readthedocs.io/en/latest/index.html):
```
import re
from django.conf import settings
from django.utils.translation import get_language
from django import forms
from django.utils import formats, timezone
class BootstrapDatePicker(forms.DateInput):
format_re = re.compile(r'(?P<part>%[bBdDjmMnyY])')
def __init__(self, attrs=None, format=None):
'''
for a list of useful attributes see:
http://bootstrap-datepicker.readthedocs.io/en/latest/options.html
Most options can be provided via data-attributes. An option can be
converted to a data-attribute by taking its name, replacing each
uppercase letter with its lowercase equivalent preceded by a dash, and
prepending "data-date-" to the result. For example, startDate would be
data-date-start-date, format would be data-date-format, and
daysOfWeekDisabled would be data-date-days-of-week-disabled.
'''
# final_attrs provides:
# - data-provide: apply datepicker to inline created inputs
# - data-date-language: apply the current language
# - data-date-format: apply the current format for dates
final_attrs = {
'data-provide': 'datepicker',
'data-date-language': get_language(),
'data-date-format': self.get_date_format(format=format),
'data-date-autoclose': 'true',
'data-date-clear-btn': 'true',
'data-date-today-btn': 'linked',
'data-date-today-highlight': 'true',
}
if attrs is not None:
classes = attrs.get('class', '').split(' ')
classes.append('datepicker')
attrs['class'] = ' '.join(classes)
final_attrs.update(attrs)
super(BootstrapDatePicker, self).__init__(attrs=final_attrs, format=format)
def get_date_format(self, format=None):
format_map = {
'%d': 'dd',
'%j': 'd',
'%m': 'mm',
'%n': 'm',
'%y': 'yy',
'%Y': 'yyyy',
'%b': 'M',
'%B': 'MM',
}
if format is None:
format = formats.get_format(self.format_key)[0]
return re.sub(self.format_re, lambda x: format_map[x.group()], format)
@property
def media(self):
root = 'vendor/bootstrap-datepicker'
css = {'screen': ('vendor/bootstrap-datepicker/css/bootstrap-datepicker3.min.css',)}
js = ['%s/js/bootstrap-datepicker.min.js' % root]
js += ['%s/locales/bootstrap-datepicker.%s.min.js' % (root, lang) for lang, _ in settings.LANGUAGES]
return forms.Media(js=js, css=css)
```
Then I implemented my form using BootstrapDatePicker custom class:
```
class MyModelForm(BootstrapForm, forms.ModelForm):
class Meta:
model = myModel
fields = ('field1', 'field2', 'date')
widgets = {
'data': BootstrapDateTimePicker(attrs={'class': 'form-control'}),
}
```
Finally I included js/css in the template. | While there is a python package that seems to solve this quite well I chose to see if I could make the datepicker work using Django's [widget](https://docs.djangoproject.com/en/1.9/ref/forms/widgets/#widget) class to render datepicker attributes, mentioned in the [docs](https://eonasdan.github.io/bootstrap-datetimepicker/).
**Note, I am only using a date field and not a date time field because I do not need my app to support times in this instance.**
**models.py**
```
class MyModel(models.Model):
...
date = models.DateField()
...
```
**forms.py**
```
class MyForm(forms.Form):
...
'''
Here I create a dict of the HTML attributes
I want to pass to the template.
'''
DATEPICKER = {
'type': 'text',
'class': 'form-control',
'id': 'datetimepicker4'
}
# Call attrs with form widget
date = forms.DateField(widget=forms.DateInput(attrs=DATEPICKER))
...
```
**template.html**
```
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
{{ form.date }}
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
```
**JS**
```
$(function () {
$('#datetimepicker1').datetimepicker({
format: 'YYYY-MM-DD' //This is the default date format Django will accept, it also disables the time in the datepicker.
})
});
``` |
28,148,125 | I want to use the bootstrap-datepicker (<https://bootstrap-datepicker.readthedocs.org>) in my django application. I use Django 1.7.
In index.html file I have:
```
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap-theme.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/js/bootstrap-datepicker.js' %}">
<link rel="stylesheet" href="{% static 'my_app/css/datepicker.css' %}">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
```
In my forms.py I have:
```
class Filter(django_filters.FilterSet):
class Meta:
model = MyModel
fields = ['user', 'date_from', 'date_to']
widgets = {'date': forms.DateInput(attrs={'class':'datepicker'})}
```
I my model.py I use to set date:
```
date_from = models.DateField()
date_to = models.DateField()
```
When I'm going through the page with the date - does not work in input area. | 2015/01/26 | [
"https://Stackoverflow.com/questions/28148125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2962768/"
] | **Update: Warning, this suggestion uses the dateTIMEpicker instead of datepicker. I suggested this because you don't have to use the time functionality of the datetimepicker, so it was quite handy in my case.**
Since I have been trying to get datetimepicker to work (in combination with a model form) for quite some time, I thought I would post the solution, that feels like an accumulation of all stackoverflow posts on this topic ;)
So, first of all, make sure to also include **[moment.js](http://momentjs.com/)**, as it is required by bootstrap-datetimepicker (see [this stackoverflow post](https://stackoverflow.com/a/21459914/5353710)). The order is important, see the mentioned post.
Then use [this site](https://eonasdan.github.io/bootstrap-datetimepicker/) to get the type of datetimepicker you need. If you have no model form in which you want to embed the datetimepicker, you should be fine with just copying that into your html code.
If you want to make one of your model forms field a fancy datepicker (without time) field like I did, then do the following:
**base.html**
```
<script type="text/javascript" src="scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="scripts/moment-2.4.0.js"></script>
<script type="text/javascript" src="scripts/bootstrap-datetimepicker.js"></script>
```
**forms.py**
```
class MyForm(forms.ModelForm):
class Meta:
...
widgets = {'myDateField': forms.DateInput(attrs={'id': 'datetimepicker12'})}
...
```
**myForm.html:**
```
<div class="row">
...
{% bootstrap_form form %}
...
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker12').datetimepicker({
inline: true,
sideBySide: true,
format: 'DD.MM.YYYY' /*remove this line if you want to use time as well */
});
});
</script>
```
I hope I was able to save you some time :) | **For DJango version 2.1, 2.0, 1.11, 1.10 and 1.8**
To use Bootstrap date-picker in your Django app install [django-bootstrap-datepicker-plus](https://github.com/monim67/django-bootstrap-datepicker-plus), follow the [installation instructions](https://github.com/monim67/django-bootstrap-datepicker-plus#installing) on the GitHub page to configure it, then you can use it in Custom Forms and Model Forms as below.
**Usage in Custom Forms:**
```
from bootstrap_datepicker_plus import DatePickerInput
class ToDoForm(forms.Form):
user = forms.CharField()
date_from = forms.DateField(widget = DatePickerInput())
```
**Usage in Model Forms**:
```
from bootstrap_datepicker_plus import DatePickerInput
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['user', 'date_from', 'date_to']
widgets = {
'date_form': DatePickerInput(),
'date_to': DatePickerInput()
}
```
**Usage with django-filters:**
```
from bootstrap_datepicker_plus import DatePickerInput
class Filter(django_filters.FilterSet):
class Meta:
model = MyModel
fields = ['user', 'date_from', 'date_to']
widgets = {'date': DatePickerInput()}
```
**Disclaimer:** *This django package is maintained by me. For any issues with it please [open issues](https://github.com/monim67/django-bootstrap-datepicker-plus/issues/new) on the Github Page instead of putting comments here.* |
28,148,125 | I want to use the bootstrap-datepicker (<https://bootstrap-datepicker.readthedocs.org>) in my django application. I use Django 1.7.
In index.html file I have:
```
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap-theme.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/js/bootstrap-datepicker.js' %}">
<link rel="stylesheet" href="{% static 'my_app/css/datepicker.css' %}">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
```
In my forms.py I have:
```
class Filter(django_filters.FilterSet):
class Meta:
model = MyModel
fields = ['user', 'date_from', 'date_to']
widgets = {'date': forms.DateInput(attrs={'class':'datepicker'})}
```
I my model.py I use to set date:
```
date_from = models.DateField()
date_to = models.DateField()
```
When I'm going through the page with the date - does not work in input area. | 2015/01/26 | [
"https://Stackoverflow.com/questions/28148125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2962768/"
] | **Update: Warning, this suggestion uses the dateTIMEpicker instead of datepicker. I suggested this because you don't have to use the time functionality of the datetimepicker, so it was quite handy in my case.**
Since I have been trying to get datetimepicker to work (in combination with a model form) for quite some time, I thought I would post the solution, that feels like an accumulation of all stackoverflow posts on this topic ;)
So, first of all, make sure to also include **[moment.js](http://momentjs.com/)**, as it is required by bootstrap-datetimepicker (see [this stackoverflow post](https://stackoverflow.com/a/21459914/5353710)). The order is important, see the mentioned post.
Then use [this site](https://eonasdan.github.io/bootstrap-datetimepicker/) to get the type of datetimepicker you need. If you have no model form in which you want to embed the datetimepicker, you should be fine with just copying that into your html code.
If you want to make one of your model forms field a fancy datepicker (without time) field like I did, then do the following:
**base.html**
```
<script type="text/javascript" src="scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="scripts/moment-2.4.0.js"></script>
<script type="text/javascript" src="scripts/bootstrap-datetimepicker.js"></script>
```
**forms.py**
```
class MyForm(forms.ModelForm):
class Meta:
...
widgets = {'myDateField': forms.DateInput(attrs={'id': 'datetimepicker12'})}
...
```
**myForm.html:**
```
<div class="row">
...
{% bootstrap_form form %}
...
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker12').datetimepicker({
inline: true,
sideBySide: true,
format: 'DD.MM.YYYY' /*remove this line if you want to use time as well */
});
});
</script>
```
I hope I was able to save you some time :) | (*Django 2.1, 1.11* and python >*2.7* and > *3.4* compatible) Working and **reusable** solution, custom from [bootstrap-datepicker](https://bootstrap-datepicker.readthedocs.io/en/latest/index.html):
```
import re
from django.conf import settings
from django.utils.translation import get_language
from django import forms
from django.utils import formats, timezone
class BootstrapDatePicker(forms.DateInput):
format_re = re.compile(r'(?P<part>%[bBdDjmMnyY])')
def __init__(self, attrs=None, format=None):
'''
for a list of useful attributes see:
http://bootstrap-datepicker.readthedocs.io/en/latest/options.html
Most options can be provided via data-attributes. An option can be
converted to a data-attribute by taking its name, replacing each
uppercase letter with its lowercase equivalent preceded by a dash, and
prepending "data-date-" to the result. For example, startDate would be
data-date-start-date, format would be data-date-format, and
daysOfWeekDisabled would be data-date-days-of-week-disabled.
'''
# final_attrs provides:
# - data-provide: apply datepicker to inline created inputs
# - data-date-language: apply the current language
# - data-date-format: apply the current format for dates
final_attrs = {
'data-provide': 'datepicker',
'data-date-language': get_language(),
'data-date-format': self.get_date_format(format=format),
'data-date-autoclose': 'true',
'data-date-clear-btn': 'true',
'data-date-today-btn': 'linked',
'data-date-today-highlight': 'true',
}
if attrs is not None:
classes = attrs.get('class', '').split(' ')
classes.append('datepicker')
attrs['class'] = ' '.join(classes)
final_attrs.update(attrs)
super(BootstrapDatePicker, self).__init__(attrs=final_attrs, format=format)
def get_date_format(self, format=None):
format_map = {
'%d': 'dd',
'%j': 'd',
'%m': 'mm',
'%n': 'm',
'%y': 'yy',
'%Y': 'yyyy',
'%b': 'M',
'%B': 'MM',
}
if format is None:
format = formats.get_format(self.format_key)[0]
return re.sub(self.format_re, lambda x: format_map[x.group()], format)
@property
def media(self):
root = 'vendor/bootstrap-datepicker'
css = {'screen': ('vendor/bootstrap-datepicker/css/bootstrap-datepicker3.min.css',)}
js = ['%s/js/bootstrap-datepicker.min.js' % root]
js += ['%s/locales/bootstrap-datepicker.%s.min.js' % (root, lang) for lang, _ in settings.LANGUAGES]
return forms.Media(js=js, css=css)
```
Then I implemented my form using BootstrapDatePicker custom class:
```
class MyModelForm(BootstrapForm, forms.ModelForm):
class Meta:
model = myModel
fields = ('field1', 'field2', 'date')
widgets = {
'data': BootstrapDateTimePicker(attrs={'class': 'form-control'}),
}
```
Finally I included js/css in the template. |
52,527 | If astronauts could deliver a large quantity of breathable air to somewhere with lower gravity, such as Earth's moon, would the air form an atmosphere, or would it float away and disappear? Is there a minimum amount of gravity necessary to trap a breathable atmosphere on a planet? | 2013/01/30 | [
"https://physics.stackexchange.com/questions/52527",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/20378/"
] | The escape velocity at the moon's surface is about 2.4 km/s. The mean speed of oxygen at 293 K is about 0.48 km/s.
A commonly quoted rule of thumb says that the escape velocity needs to be 6 times the gas's mean velocity in order for that gas to remain captive to gravity and the values I quoted are related by a factor of only 5. The air would contain water (since dry air is very uncomfortable to breath) and carbon dioxide (as a by-product if not also needed to sustain the cyanobacteria/plants you would want in place of planetary size mechanical carbon dioxide scrubbers, then there are the nutrients you would need to sustain those) which would readily exacerbate an atmospheric greenhouse effect and, with the moon being at about the same distance from the sun as is earth, you would expect the air to warm up to similar to earth temperatures, though without the moderating effect of oceans, and so cause the oxygen to dissipate. As nitrogen is lighter it's mean speed at the same temp is higher, v\_rms something like 0.51 km/s IIRC, so it too would dissipate as would water vapour.
In short, it doesn't seem likely that it would be possible on the moon.
As an aside, ignoring for a moment shielding from the solar wind noted by turscher, Venus and Earth have similar surface gravities but Venus' atmosphere is much thicker than Earth's so gravity is not the sole factor in determining atmospheric retention and neither is temperature as Venus is very much hotter than Earth.
To answer the part of your question about a minimum gravity needed which no one else seems to have addressed:
Surface gravity would have to be such that it requires a escape velocity around, as that rule of thumb states, six times the v\_rms of any gases you wished to retain. With a too low escape velocity over time gases will escape, lighter gases first, leading to a thinning of the atmosphere and a time-dependent composition. But this could take geologic ages. Any particular loss process could be so slow that it would be easily replenished by whatever process the astronauts used to create the atmosphere. If part of that process was bombardment by comets (largely for their water content) care would have to be taken as such extra-planetary bombardment could also be very damaging to a planet's atmosphere. | The speed of oxygen at room temperature (293k) is 1720km per hour so if the escape velocity of the moon or planet is greater than that then at least you will have oxygen. If you want some nitrogen in the mix then you will have to google it's speed like I did for oxygen;-) |
52,527 | If astronauts could deliver a large quantity of breathable air to somewhere with lower gravity, such as Earth's moon, would the air form an atmosphere, or would it float away and disappear? Is there a minimum amount of gravity necessary to trap a breathable atmosphere on a planet? | 2013/01/30 | [
"https://physics.stackexchange.com/questions/52527",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/20378/"
] | The gravity of a planet holds the atmosphere in place. The moon doesn't have enough mass / gravity to do so. If you moved air to the moon there's so little gravity the air would simply float away. | The speed of oxygen at room temperature (293k) is 1720km per hour so if the escape velocity of the moon or planet is greater than that then at least you will have oxygen. If you want some nitrogen in the mix then you will have to google it's speed like I did for oxygen;-) |
52,527 | If astronauts could deliver a large quantity of breathable air to somewhere with lower gravity, such as Earth's moon, would the air form an atmosphere, or would it float away and disappear? Is there a minimum amount of gravity necessary to trap a breathable atmosphere on a planet? | 2013/01/30 | [
"https://physics.stackexchange.com/questions/52527",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/20378/"
] | The escape velocity at the moon's surface is about 2.4 km/s. The mean speed of oxygen at 293 K is about 0.48 km/s.
A commonly quoted rule of thumb says that the escape velocity needs to be 6 times the gas's mean velocity in order for that gas to remain captive to gravity and the values I quoted are related by a factor of only 5. The air would contain water (since dry air is very uncomfortable to breath) and carbon dioxide (as a by-product if not also needed to sustain the cyanobacteria/plants you would want in place of planetary size mechanical carbon dioxide scrubbers, then there are the nutrients you would need to sustain those) which would readily exacerbate an atmospheric greenhouse effect and, with the moon being at about the same distance from the sun as is earth, you would expect the air to warm up to similar to earth temperatures, though without the moderating effect of oceans, and so cause the oxygen to dissipate. As nitrogen is lighter it's mean speed at the same temp is higher, v\_rms something like 0.51 km/s IIRC, so it too would dissipate as would water vapour.
In short, it doesn't seem likely that it would be possible on the moon.
As an aside, ignoring for a moment shielding from the solar wind noted by turscher, Venus and Earth have similar surface gravities but Venus' atmosphere is much thicker than Earth's so gravity is not the sole factor in determining atmospheric retention and neither is temperature as Venus is very much hotter than Earth.
To answer the part of your question about a minimum gravity needed which no one else seems to have addressed:
Surface gravity would have to be such that it requires a escape velocity around, as that rule of thumb states, six times the v\_rms of any gases you wished to retain. With a too low escape velocity over time gases will escape, lighter gases first, leading to a thinning of the atmosphere and a time-dependent composition. But this could take geologic ages. Any particular loss process could be so slow that it would be easily replenished by whatever process the astronauts used to create the atmosphere. If part of that process was bombardment by comets (largely for their water content) care would have to be taken as such extra-planetary bombardment could also be very damaging to a planet's atmosphere. | The gravity of a planet holds the atmosphere in place. The moon doesn't have enough mass / gravity to do so. If you moved air to the moon there's so little gravity the air would simply float away. |
52,527 | If astronauts could deliver a large quantity of breathable air to somewhere with lower gravity, such as Earth's moon, would the air form an atmosphere, or would it float away and disappear? Is there a minimum amount of gravity necessary to trap a breathable atmosphere on a planet? | 2013/01/30 | [
"https://physics.stackexchange.com/questions/52527",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/20378/"
] | The escape velocity at the moon's surface is about 2.4 km/s. The mean speed of oxygen at 293 K is about 0.48 km/s.
A commonly quoted rule of thumb says that the escape velocity needs to be 6 times the gas's mean velocity in order for that gas to remain captive to gravity and the values I quoted are related by a factor of only 5. The air would contain water (since dry air is very uncomfortable to breath) and carbon dioxide (as a by-product if not also needed to sustain the cyanobacteria/plants you would want in place of planetary size mechanical carbon dioxide scrubbers, then there are the nutrients you would need to sustain those) which would readily exacerbate an atmospheric greenhouse effect and, with the moon being at about the same distance from the sun as is earth, you would expect the air to warm up to similar to earth temperatures, though without the moderating effect of oceans, and so cause the oxygen to dissipate. As nitrogen is lighter it's mean speed at the same temp is higher, v\_rms something like 0.51 km/s IIRC, so it too would dissipate as would water vapour.
In short, it doesn't seem likely that it would be possible on the moon.
As an aside, ignoring for a moment shielding from the solar wind noted by turscher, Venus and Earth have similar surface gravities but Venus' atmosphere is much thicker than Earth's so gravity is not the sole factor in determining atmospheric retention and neither is temperature as Venus is very much hotter than Earth.
To answer the part of your question about a minimum gravity needed which no one else seems to have addressed:
Surface gravity would have to be such that it requires a escape velocity around, as that rule of thumb states, six times the v\_rms of any gases you wished to retain. With a too low escape velocity over time gases will escape, lighter gases first, leading to a thinning of the atmosphere and a time-dependent composition. But this could take geologic ages. Any particular loss process could be so slow that it would be easily replenished by whatever process the astronauts used to create the atmosphere. If part of that process was bombardment by comets (largely for their water content) care would have to be taken as such extra-planetary bombardment could also be very damaging to a planet's atmosphere. | The moon has 85% of the gravity of Titan (which has a thick hydrocarbon atmosphere), so I cannot believe for 1 second that it's gravity is too weak to retain a viable atmosphere.
Factors like Sola winds stripping the atmosphere due to lack of protection from a magnetic field, is a valid explanation, but low gravity cannot be, because the existence of Titan disproves that. |
52,527 | If astronauts could deliver a large quantity of breathable air to somewhere with lower gravity, such as Earth's moon, would the air form an atmosphere, or would it float away and disappear? Is there a minimum amount of gravity necessary to trap a breathable atmosphere on a planet? | 2013/01/30 | [
"https://physics.stackexchange.com/questions/52527",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/20378/"
] | The moon has 85% of the gravity of Titan (which has a thick hydrocarbon atmosphere), so I cannot believe for 1 second that it's gravity is too weak to retain a viable atmosphere.
Factors like Sola winds stripping the atmosphere due to lack of protection from a magnetic field, is a valid explanation, but low gravity cannot be, because the existence of Titan disproves that. | The speed of oxygen at room temperature (293k) is 1720km per hour so if the escape velocity of the moon or planet is greater than that then at least you will have oxygen. If you want some nitrogen in the mix then you will have to google it's speed like I did for oxygen;-) |
52,527 | If astronauts could deliver a large quantity of breathable air to somewhere with lower gravity, such as Earth's moon, would the air form an atmosphere, or would it float away and disappear? Is there a minimum amount of gravity necessary to trap a breathable atmosphere on a planet? | 2013/01/30 | [
"https://physics.stackexchange.com/questions/52527",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/20378/"
] | Gravity is a major factor in planets retaining atmospheres over the eons. But there are other factors that must be taken into consideration to consider the volatility of an atmosphere.
Solar wind is the main factor of erosion on any atmosphere. But a healthy magnetic field can deflect most of the solar radiation and decrease the erosion. It has been a matter of debate recently if exo-moons of jovian planets in habitable zones of their host stars would be able to sustain atmospheres: such moons are most likely tidally-locked, so their magnetic fields are not expected to be high, but their host planets will likely have strong radiation belts. But is not clear at the moment if the radiation belts will protect or erode the atmosphere. Saturn has a benign level of radiation, so we have Titan, which has an atmosphere that is thicker than earth's | The escape velocity at the moon's surface is about 2.4 km/s. The mean speed of oxygen at 293 K is about 0.48 km/s.
A commonly quoted rule of thumb says that the escape velocity needs to be 6 times the gas's mean velocity in order for that gas to remain captive to gravity and the values I quoted are related by a factor of only 5. The air would contain water (since dry air is very uncomfortable to breath) and carbon dioxide (as a by-product if not also needed to sustain the cyanobacteria/plants you would want in place of planetary size mechanical carbon dioxide scrubbers, then there are the nutrients you would need to sustain those) which would readily exacerbate an atmospheric greenhouse effect and, with the moon being at about the same distance from the sun as is earth, you would expect the air to warm up to similar to earth temperatures, though without the moderating effect of oceans, and so cause the oxygen to dissipate. As nitrogen is lighter it's mean speed at the same temp is higher, v\_rms something like 0.51 km/s IIRC, so it too would dissipate as would water vapour.
In short, it doesn't seem likely that it would be possible on the moon.
As an aside, ignoring for a moment shielding from the solar wind noted by turscher, Venus and Earth have similar surface gravities but Venus' atmosphere is much thicker than Earth's so gravity is not the sole factor in determining atmospheric retention and neither is temperature as Venus is very much hotter than Earth.
To answer the part of your question about a minimum gravity needed which no one else seems to have addressed:
Surface gravity would have to be such that it requires a escape velocity around, as that rule of thumb states, six times the v\_rms of any gases you wished to retain. With a too low escape velocity over time gases will escape, lighter gases first, leading to a thinning of the atmosphere and a time-dependent composition. But this could take geologic ages. Any particular loss process could be so slow that it would be easily replenished by whatever process the astronauts used to create the atmosphere. If part of that process was bombardment by comets (largely for their water content) care would have to be taken as such extra-planetary bombardment could also be very damaging to a planet's atmosphere. |
52,527 | If astronauts could deliver a large quantity of breathable air to somewhere with lower gravity, such as Earth's moon, would the air form an atmosphere, or would it float away and disappear? Is there a minimum amount of gravity necessary to trap a breathable atmosphere on a planet? | 2013/01/30 | [
"https://physics.stackexchange.com/questions/52527",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/20378/"
] | Gravity is a major factor in planets retaining atmospheres over the eons. But there are other factors that must be taken into consideration to consider the volatility of an atmosphere.
Solar wind is the main factor of erosion on any atmosphere. But a healthy magnetic field can deflect most of the solar radiation and decrease the erosion. It has been a matter of debate recently if exo-moons of jovian planets in habitable zones of their host stars would be able to sustain atmospheres: such moons are most likely tidally-locked, so their magnetic fields are not expected to be high, but their host planets will likely have strong radiation belts. But is not clear at the moment if the radiation belts will protect or erode the atmosphere. Saturn has a benign level of radiation, so we have Titan, which has an atmosphere that is thicker than earth's | The gravity of a planet holds the atmosphere in place. The moon doesn't have enough mass / gravity to do so. If you moved air to the moon there's so little gravity the air would simply float away. |
52,527 | If astronauts could deliver a large quantity of breathable air to somewhere with lower gravity, such as Earth's moon, would the air form an atmosphere, or would it float away and disappear? Is there a minimum amount of gravity necessary to trap a breathable atmosphere on a planet? | 2013/01/30 | [
"https://physics.stackexchange.com/questions/52527",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/20378/"
] | Gravity is a major factor in planets retaining atmospheres over the eons. But there are other factors that must be taken into consideration to consider the volatility of an atmosphere.
Solar wind is the main factor of erosion on any atmosphere. But a healthy magnetic field can deflect most of the solar radiation and decrease the erosion. It has been a matter of debate recently if exo-moons of jovian planets in habitable zones of their host stars would be able to sustain atmospheres: such moons are most likely tidally-locked, so their magnetic fields are not expected to be high, but their host planets will likely have strong radiation belts. But is not clear at the moment if the radiation belts will protect or erode the atmosphere. Saturn has a benign level of radiation, so we have Titan, which has an atmosphere that is thicker than earth's | The moon has 85% of the gravity of Titan (which has a thick hydrocarbon atmosphere), so I cannot believe for 1 second that it's gravity is too weak to retain a viable atmosphere.
Factors like Sola winds stripping the atmosphere due to lack of protection from a magnetic field, is a valid explanation, but low gravity cannot be, because the existence of Titan disproves that. |
52,527 | If astronauts could deliver a large quantity of breathable air to somewhere with lower gravity, such as Earth's moon, would the air form an atmosphere, or would it float away and disappear? Is there a minimum amount of gravity necessary to trap a breathable atmosphere on a planet? | 2013/01/30 | [
"https://physics.stackexchange.com/questions/52527",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/20378/"
] | The escape velocity at the moon's surface is about 2.4 km/s. The mean speed of oxygen at 293 K is about 0.48 km/s.
A commonly quoted rule of thumb says that the escape velocity needs to be 6 times the gas's mean velocity in order for that gas to remain captive to gravity and the values I quoted are related by a factor of only 5. The air would contain water (since dry air is very uncomfortable to breath) and carbon dioxide (as a by-product if not also needed to sustain the cyanobacteria/plants you would want in place of planetary size mechanical carbon dioxide scrubbers, then there are the nutrients you would need to sustain those) which would readily exacerbate an atmospheric greenhouse effect and, with the moon being at about the same distance from the sun as is earth, you would expect the air to warm up to similar to earth temperatures, though without the moderating effect of oceans, and so cause the oxygen to dissipate. As nitrogen is lighter it's mean speed at the same temp is higher, v\_rms something like 0.51 km/s IIRC, so it too would dissipate as would water vapour.
In short, it doesn't seem likely that it would be possible on the moon.
As an aside, ignoring for a moment shielding from the solar wind noted by turscher, Venus and Earth have similar surface gravities but Venus' atmosphere is much thicker than Earth's so gravity is not the sole factor in determining atmospheric retention and neither is temperature as Venus is very much hotter than Earth.
To answer the part of your question about a minimum gravity needed which no one else seems to have addressed:
Surface gravity would have to be such that it requires a escape velocity around, as that rule of thumb states, six times the v\_rms of any gases you wished to retain. With a too low escape velocity over time gases will escape, lighter gases first, leading to a thinning of the atmosphere and a time-dependent composition. But this could take geologic ages. Any particular loss process could be so slow that it would be easily replenished by whatever process the astronauts used to create the atmosphere. If part of that process was bombardment by comets (largely for their water content) care would have to be taken as such extra-planetary bombardment could also be very damaging to a planet's atmosphere. | I guess the devil is in the details. For example, if the celestial body in question is far from its star, so its temperature is very low, it is easier to retain low-temperature air around the body. On the other hand, very cold air is not breathable anyway. There is another way though. If the astronauts can bring so much air to the body, why don't they arrange a membrane around the body to keep the air? Furthermore, they don't need the membrane around the entire body, they can arrange it just over some limited area where they want to live. On the other hand, they would need to protect such a membrane from meteorites... So I guess there is a lot they can do and a lot of factors that could make their life miserable:-) |
52,527 | If astronauts could deliver a large quantity of breathable air to somewhere with lower gravity, such as Earth's moon, would the air form an atmosphere, or would it float away and disappear? Is there a minimum amount of gravity necessary to trap a breathable atmosphere on a planet? | 2013/01/30 | [
"https://physics.stackexchange.com/questions/52527",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/20378/"
] | Gravity is a major factor in planets retaining atmospheres over the eons. But there are other factors that must be taken into consideration to consider the volatility of an atmosphere.
Solar wind is the main factor of erosion on any atmosphere. But a healthy magnetic field can deflect most of the solar radiation and decrease the erosion. It has been a matter of debate recently if exo-moons of jovian planets in habitable zones of their host stars would be able to sustain atmospheres: such moons are most likely tidally-locked, so their magnetic fields are not expected to be high, but their host planets will likely have strong radiation belts. But is not clear at the moment if the radiation belts will protect or erode the atmosphere. Saturn has a benign level of radiation, so we have Titan, which has an atmosphere that is thicker than earth's | I guess the devil is in the details. For example, if the celestial body in question is far from its star, so its temperature is very low, it is easier to retain low-temperature air around the body. On the other hand, very cold air is not breathable anyway. There is another way though. If the astronauts can bring so much air to the body, why don't they arrange a membrane around the body to keep the air? Furthermore, they don't need the membrane around the entire body, they can arrange it just over some limited area where they want to live. On the other hand, they would need to protect such a membrane from meteorites... So I guess there is a lot they can do and a lot of factors that could make their life miserable:-) |
73,287,723 | ```
Warning: Trying to access array offset on value of type null in
```
C:\xampp\htdocs\ecommerce\_cms\_tutorial\register.php on line 172
}elseif ($row\_register['email'] != $email && $password == $confirm\_password) { | 2022/08/09 | [
"https://Stackoverflow.com/questions/73287723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19407065/"
] | Given the following `application.properties` example file
```ini
toto="some value"
accessToken="atoken"
pipo="other value"
bingo=1
```
the following `sed` command:
```
sed -i 's/^\(accessToken=\).*$/\1"abcd123"/' application.properties
```
gives as a result (i.e. `cat application.properties`)
```ini
toto="some value"
accessToken="abcd123"
pipo="other value"
bingo=1
``` | ```
sed -i /s/testtobechanged/textwanted/g applications.proteries
``` |
2,920,178 | Why html agility pack is used to parse the information from the html file ? Is not there inbuilt or native library in the .net to parse the information from the html file ? If there then what is the problem with inbuilt support ? What the benefits of using html agility pack versus inbuilt support for parsing information from the html file ? | 2010/05/27 | [
"https://Stackoverflow.com/questions/2920178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/227848/"
] | There is no html parser in the BCL, which is why the HTML Agility Pack is recommended by so many. | In one of my applications, I have an HTML template saved in an HTML file. I load it and replace some nodes markers with the values. In this cases I do use .NET XMLDocuments and it works fine. At least in this controlled environment. I don't know what would happen if I tried to parse malformed HTML's.
This is a sample of my code:
```
Dim S as String = System.IO.File.ReadAllText("Mytemplate.html")
Dim dXML As New System.Xml.XmlDocument
dXML.LoadXml(S)
Dim N As System.Xml.XmlNode
N = dXML.SelectSingleNode("descendant::NodeToFind")
N.InnerText = "Text inside the node"
```
As I say, this works fine, but if you want to do something more specific to HTML, I guess it would be a good idea to use the HTML agility pack. |
25,563,455 | I need the last commit date in git. This means the latest update date in my program.
I used the command : $ `git log -1` but this command will give me the date from the local repository. Rather I need date from remote repository.
I tried some commands as follow.
```
git log -n 1 origin/Sprint-6.
git rev-parse --verify HEAD
``` | 2014/08/29 | [
"https://Stackoverflow.com/questions/25563455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989297/"
] | The following command will be helpful:
```
git log -1 --format=%cd
```
This will print the latest change date for one file. The -1 shows one log entry (the most recent), and `--format=%cd` shows the commit date.
See the documentation for [git-log](https://git-scm.com/docs/git-log) for a full description of the options. | Get the last commit date:
-------------------------
You want the "repository wide last commit date for a given git user and git project, for a given branch. For example the date is shown at the top when you visit your repo and go to `commits -> master` for example:
<https://github.com/sentientmachine/TeslaAverageGainByMonthWeekDay/commits/master>
Get the last local commit date in git using terminal
----------------------------------------------------
Use `git help log` for more info on format codes to pass to `--format` to tell git log what kind of data to fetch.
The last commit date in git:
```
git log -1 --format="%at" | xargs -I{} date -d @{} +%Y/%m/%d_%H:%M:%S
#prints 2018/07/18 07:40:52
```
But as you pointed out, you have to run that command on the machine that performed the last commit. If the last commit date was performed on another machine, the above command only reports local last commit... So:
Or Repository wide: Get the last git commit date
------------------------------------------------
Same as above, but do a git pull first
```
git pull;
git log -1 --format="%at" | xargs -I{} date -d @{} +%Y/%m/%d_%H:%M:%S
#prints 2018/07/18 09:15:10
```
Or use the JSON API:
--------------------
Doing `git pull`s is very slow and you're banging GitHub with a heavy operation. Just query the GitHub rest api:
```
#assuming you're using github and your project URL is visible to public:
# https://github.com/yourusername/your_repo_name
#then do:
curl https://api.github.com/repos/yourusername/your_repo_name/commits/master
```
That blasts you in the face with a screen full of json, so send it your favorite json parser and get the field called `date`:
```
curl https://api.github.com/repos/<your_name>/<your_repo>/commits/master 2>&1 | \
grep '"date"' | tail -n 1
#prints "date": "2019-06-05T14:38:19Z"
```
From comments below, `gedge` has handy dandy improvements to incantations:
--------------------------------------------------------------------------
```
git log -1 --date=format:"%Y/%m/%d %T" --format="%ad"
2019/11/13 15:25:44
```
Or even simpler: ( <https://git-scm.com/docs/git-log/1.8.0> )
```
git --no-pager log -1 --format="%ai"
2019-12-13 09:08:38 -0500
```
Your choices are north, south, east, and "Dennis". |
25,563,455 | I need the last commit date in git. This means the latest update date in my program.
I used the command : $ `git log -1` but this command will give me the date from the local repository. Rather I need date from remote repository.
I tried some commands as follow.
```
git log -n 1 origin/Sprint-6.
git rev-parse --verify HEAD
``` | 2014/08/29 | [
"https://Stackoverflow.com/questions/25563455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989297/"
] | The following command will be helpful:
```
git log -1 --format=%cd
```
This will print the latest change date for one file. The -1 shows one log entry (the most recent), and `--format=%cd` shows the commit date.
See the documentation for [git-log](https://git-scm.com/docs/git-log) for a full description of the options. | ### To get the last commit date from git repository in a long(Unix epoch timestamp)
* **Command:** `git log -1 --format=%ct`
* **Result:** `1605103148`
**Note:** You can visit the [git-log](https://git-scm.com/docs/git-log) documentation to get a more detailed description of the options. |
25,563,455 | I need the last commit date in git. This means the latest update date in my program.
I used the command : $ `git log -1` but this command will give me the date from the local repository. Rather I need date from remote repository.
I tried some commands as follow.
```
git log -n 1 origin/Sprint-6.
git rev-parse --verify HEAD
``` | 2014/08/29 | [
"https://Stackoverflow.com/questions/25563455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989297/"
] | The following command will be helpful:
```
git log -1 --format=%cd
```
This will print the latest change date for one file. The -1 shows one log entry (the most recent), and `--format=%cd` shows the commit date.
See the documentation for [git-log](https://git-scm.com/docs/git-log) for a full description of the options. | *git log -1* will give you the Merge id, Author and Date
*git log -1 --format=%cd* will give the output as below
**Wed Apr 13 15:32:54 2022 +0530**
We can format the date as below:
*git log -1 --pretty='format:%cd' --date=format:'%Y-%m-%d %H:%M:%S'*
output
**2022-04-13 15:32:54** |
25,563,455 | I need the last commit date in git. This means the latest update date in my program.
I used the command : $ `git log -1` but this command will give me the date from the local repository. Rather I need date from remote repository.
I tried some commands as follow.
```
git log -n 1 origin/Sprint-6.
git rev-parse --verify HEAD
``` | 2014/08/29 | [
"https://Stackoverflow.com/questions/25563455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989297/"
] | The following command will be helpful:
```
git log -1 --format=%cd
```
This will print the latest change date for one file. The -1 shows one log entry (the most recent), and `--format=%cd` shows the commit date.
See the documentation for [git-log](https://git-scm.com/docs/git-log) for a full description of the options. | Late to the party but here's how to get the UNIX timestamp of the latest remote commit:
```
git log -1 --date=raw origin/master | grep ^Date | tr -s ' ' | cut -d ' ' -f2
``` |
25,563,455 | I need the last commit date in git. This means the latest update date in my program.
I used the command : $ `git log -1` but this command will give me the date from the local repository. Rather I need date from remote repository.
I tried some commands as follow.
```
git log -n 1 origin/Sprint-6.
git rev-parse --verify HEAD
``` | 2014/08/29 | [
"https://Stackoverflow.com/questions/25563455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989297/"
] | Get the last commit date:
-------------------------
You want the "repository wide last commit date for a given git user and git project, for a given branch. For example the date is shown at the top when you visit your repo and go to `commits -> master` for example:
<https://github.com/sentientmachine/TeslaAverageGainByMonthWeekDay/commits/master>
Get the last local commit date in git using terminal
----------------------------------------------------
Use `git help log` for more info on format codes to pass to `--format` to tell git log what kind of data to fetch.
The last commit date in git:
```
git log -1 --format="%at" | xargs -I{} date -d @{} +%Y/%m/%d_%H:%M:%S
#prints 2018/07/18 07:40:52
```
But as you pointed out, you have to run that command on the machine that performed the last commit. If the last commit date was performed on another machine, the above command only reports local last commit... So:
Or Repository wide: Get the last git commit date
------------------------------------------------
Same as above, but do a git pull first
```
git pull;
git log -1 --format="%at" | xargs -I{} date -d @{} +%Y/%m/%d_%H:%M:%S
#prints 2018/07/18 09:15:10
```
Or use the JSON API:
--------------------
Doing `git pull`s is very slow and you're banging GitHub with a heavy operation. Just query the GitHub rest api:
```
#assuming you're using github and your project URL is visible to public:
# https://github.com/yourusername/your_repo_name
#then do:
curl https://api.github.com/repos/yourusername/your_repo_name/commits/master
```
That blasts you in the face with a screen full of json, so send it your favorite json parser and get the field called `date`:
```
curl https://api.github.com/repos/<your_name>/<your_repo>/commits/master 2>&1 | \
grep '"date"' | tail -n 1
#prints "date": "2019-06-05T14:38:19Z"
```
From comments below, `gedge` has handy dandy improvements to incantations:
--------------------------------------------------------------------------
```
git log -1 --date=format:"%Y/%m/%d %T" --format="%ad"
2019/11/13 15:25:44
```
Or even simpler: ( <https://git-scm.com/docs/git-log/1.8.0> )
```
git --no-pager log -1 --format="%ai"
2019-12-13 09:08:38 -0500
```
Your choices are north, south, east, and "Dennis". | ### To get the last commit date from git repository in a long(Unix epoch timestamp)
* **Command:** `git log -1 --format=%ct`
* **Result:** `1605103148`
**Note:** You can visit the [git-log](https://git-scm.com/docs/git-log) documentation to get a more detailed description of the options. |
25,563,455 | I need the last commit date in git. This means the latest update date in my program.
I used the command : $ `git log -1` but this command will give me the date from the local repository. Rather I need date from remote repository.
I tried some commands as follow.
```
git log -n 1 origin/Sprint-6.
git rev-parse --verify HEAD
``` | 2014/08/29 | [
"https://Stackoverflow.com/questions/25563455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989297/"
] | Get the last commit date:
-------------------------
You want the "repository wide last commit date for a given git user and git project, for a given branch. For example the date is shown at the top when you visit your repo and go to `commits -> master` for example:
<https://github.com/sentientmachine/TeslaAverageGainByMonthWeekDay/commits/master>
Get the last local commit date in git using terminal
----------------------------------------------------
Use `git help log` for more info on format codes to pass to `--format` to tell git log what kind of data to fetch.
The last commit date in git:
```
git log -1 --format="%at" | xargs -I{} date -d @{} +%Y/%m/%d_%H:%M:%S
#prints 2018/07/18 07:40:52
```
But as you pointed out, you have to run that command on the machine that performed the last commit. If the last commit date was performed on another machine, the above command only reports local last commit... So:
Or Repository wide: Get the last git commit date
------------------------------------------------
Same as above, but do a git pull first
```
git pull;
git log -1 --format="%at" | xargs -I{} date -d @{} +%Y/%m/%d_%H:%M:%S
#prints 2018/07/18 09:15:10
```
Or use the JSON API:
--------------------
Doing `git pull`s is very slow and you're banging GitHub with a heavy operation. Just query the GitHub rest api:
```
#assuming you're using github and your project URL is visible to public:
# https://github.com/yourusername/your_repo_name
#then do:
curl https://api.github.com/repos/yourusername/your_repo_name/commits/master
```
That blasts you in the face with a screen full of json, so send it your favorite json parser and get the field called `date`:
```
curl https://api.github.com/repos/<your_name>/<your_repo>/commits/master 2>&1 | \
grep '"date"' | tail -n 1
#prints "date": "2019-06-05T14:38:19Z"
```
From comments below, `gedge` has handy dandy improvements to incantations:
--------------------------------------------------------------------------
```
git log -1 --date=format:"%Y/%m/%d %T" --format="%ad"
2019/11/13 15:25:44
```
Or even simpler: ( <https://git-scm.com/docs/git-log/1.8.0> )
```
git --no-pager log -1 --format="%ai"
2019-12-13 09:08:38 -0500
```
Your choices are north, south, east, and "Dennis". | *git log -1* will give you the Merge id, Author and Date
*git log -1 --format=%cd* will give the output as below
**Wed Apr 13 15:32:54 2022 +0530**
We can format the date as below:
*git log -1 --pretty='format:%cd' --date=format:'%Y-%m-%d %H:%M:%S'*
output
**2022-04-13 15:32:54** |
25,563,455 | I need the last commit date in git. This means the latest update date in my program.
I used the command : $ `git log -1` but this command will give me the date from the local repository. Rather I need date from remote repository.
I tried some commands as follow.
```
git log -n 1 origin/Sprint-6.
git rev-parse --verify HEAD
``` | 2014/08/29 | [
"https://Stackoverflow.com/questions/25563455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989297/"
] | Get the last commit date:
-------------------------
You want the "repository wide last commit date for a given git user and git project, for a given branch. For example the date is shown at the top when you visit your repo and go to `commits -> master` for example:
<https://github.com/sentientmachine/TeslaAverageGainByMonthWeekDay/commits/master>
Get the last local commit date in git using terminal
----------------------------------------------------
Use `git help log` for more info on format codes to pass to `--format` to tell git log what kind of data to fetch.
The last commit date in git:
```
git log -1 --format="%at" | xargs -I{} date -d @{} +%Y/%m/%d_%H:%M:%S
#prints 2018/07/18 07:40:52
```
But as you pointed out, you have to run that command on the machine that performed the last commit. If the last commit date was performed on another machine, the above command only reports local last commit... So:
Or Repository wide: Get the last git commit date
------------------------------------------------
Same as above, but do a git pull first
```
git pull;
git log -1 --format="%at" | xargs -I{} date -d @{} +%Y/%m/%d_%H:%M:%S
#prints 2018/07/18 09:15:10
```
Or use the JSON API:
--------------------
Doing `git pull`s is very slow and you're banging GitHub with a heavy operation. Just query the GitHub rest api:
```
#assuming you're using github and your project URL is visible to public:
# https://github.com/yourusername/your_repo_name
#then do:
curl https://api.github.com/repos/yourusername/your_repo_name/commits/master
```
That blasts you in the face with a screen full of json, so send it your favorite json parser and get the field called `date`:
```
curl https://api.github.com/repos/<your_name>/<your_repo>/commits/master 2>&1 | \
grep '"date"' | tail -n 1
#prints "date": "2019-06-05T14:38:19Z"
```
From comments below, `gedge` has handy dandy improvements to incantations:
--------------------------------------------------------------------------
```
git log -1 --date=format:"%Y/%m/%d %T" --format="%ad"
2019/11/13 15:25:44
```
Or even simpler: ( <https://git-scm.com/docs/git-log/1.8.0> )
```
git --no-pager log -1 --format="%ai"
2019-12-13 09:08:38 -0500
```
Your choices are north, south, east, and "Dennis". | Late to the party but here's how to get the UNIX timestamp of the latest remote commit:
```
git log -1 --date=raw origin/master | grep ^Date | tr -s ' ' | cut -d ' ' -f2
``` |
25,563,455 | I need the last commit date in git. This means the latest update date in my program.
I used the command : $ `git log -1` but this command will give me the date from the local repository. Rather I need date from remote repository.
I tried some commands as follow.
```
git log -n 1 origin/Sprint-6.
git rev-parse --verify HEAD
``` | 2014/08/29 | [
"https://Stackoverflow.com/questions/25563455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989297/"
] | ### To get the last commit date from git repository in a long(Unix epoch timestamp)
* **Command:** `git log -1 --format=%ct`
* **Result:** `1605103148`
**Note:** You can visit the [git-log](https://git-scm.com/docs/git-log) documentation to get a more detailed description of the options. | *git log -1* will give you the Merge id, Author and Date
*git log -1 --format=%cd* will give the output as below
**Wed Apr 13 15:32:54 2022 +0530**
We can format the date as below:
*git log -1 --pretty='format:%cd' --date=format:'%Y-%m-%d %H:%M:%S'*
output
**2022-04-13 15:32:54** |
25,563,455 | I need the last commit date in git. This means the latest update date in my program.
I used the command : $ `git log -1` but this command will give me the date from the local repository. Rather I need date from remote repository.
I tried some commands as follow.
```
git log -n 1 origin/Sprint-6.
git rev-parse --verify HEAD
``` | 2014/08/29 | [
"https://Stackoverflow.com/questions/25563455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989297/"
] | ### To get the last commit date from git repository in a long(Unix epoch timestamp)
* **Command:** `git log -1 --format=%ct`
* **Result:** `1605103148`
**Note:** You can visit the [git-log](https://git-scm.com/docs/git-log) documentation to get a more detailed description of the options. | Late to the party but here's how to get the UNIX timestamp of the latest remote commit:
```
git log -1 --date=raw origin/master | grep ^Date | tr -s ' ' | cut -d ' ' -f2
``` |
25,563,455 | I need the last commit date in git. This means the latest update date in my program.
I used the command : $ `git log -1` but this command will give me the date from the local repository. Rather I need date from remote repository.
I tried some commands as follow.
```
git log -n 1 origin/Sprint-6.
git rev-parse --verify HEAD
``` | 2014/08/29 | [
"https://Stackoverflow.com/questions/25563455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3989297/"
] | Late to the party but here's how to get the UNIX timestamp of the latest remote commit:
```
git log -1 --date=raw origin/master | grep ^Date | tr -s ' ' | cut -d ' ' -f2
``` | *git log -1* will give you the Merge id, Author and Date
*git log -1 --format=%cd* will give the output as below
**Wed Apr 13 15:32:54 2022 +0530**
We can format the date as below:
*git log -1 --pretty='format:%cd' --date=format:'%Y-%m-%d %H:%M:%S'*
output
**2022-04-13 15:32:54** |
7,420,815 | I am looking for a nice and fast way of applying some arbitrary function which operates on vectors, such as `sum`, consecutively to a subvector of consecutive K elements.
Here is one simple example, which should illustrate very clearly what I want:
```
v <- c(1, 2, 3, 4, 5, 6, 7, 8)
v2 <- myapply(v, sum, group_size=3) # v2 should be equal to c(6, 15, 15)
```
The function should try to process groups of `group_size` elements of a given vector and apply a function to each group (treating it as another vector). In this example, the vector `v2` is obtained as follows: (1 + 2 + 3) = 6, (4 + 5 + 6) = 15, (7 + 8) = 15. In this case, the K did not divide N exactly, so the last group was of size less then K.
If there is a nicer/faster solution which only works if N is a multiple of K, I would also appreciate it. | 2011/09/14 | [
"https://Stackoverflow.com/questions/7420815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/395744/"
] | Try this:
```
library(zoo)
rollapply(v, 3, by = 3, sum, partial = TRUE, align = "left")
## [1] 6 15 15
```
or
```
apply(matrix(c(v, rep(NA, 3 - length(v) %% 3)), 3), 2, sum, na.rm = TRUE)
## [1] 6 15 15
```
Also, in the case of `sum` the last one could be shortened to
```
colSums(matrix(c(v, rep(0, 3 - length(v) %% 3)), 3))
``` | As @Chase said in a comment, you can create your own grouping variable and then use that. Wrapping that process into a function would look like
```
myapply <- function(v, fun, group_size=1) {
unname(tapply(v, (seq_along(v)-1) %/% group_size, fun))
}
```
which gives your results
```
> myapply(v, sum, group_size=3)
[1] 6 15 15
```
Note this does not require the length of `v` to be a multiple of the `group_size`. |
7,420,815 | I am looking for a nice and fast way of applying some arbitrary function which operates on vectors, such as `sum`, consecutively to a subvector of consecutive K elements.
Here is one simple example, which should illustrate very clearly what I want:
```
v <- c(1, 2, 3, 4, 5, 6, 7, 8)
v2 <- myapply(v, sum, group_size=3) # v2 should be equal to c(6, 15, 15)
```
The function should try to process groups of `group_size` elements of a given vector and apply a function to each group (treating it as another vector). In this example, the vector `v2` is obtained as follows: (1 + 2 + 3) = 6, (4 + 5 + 6) = 15, (7 + 8) = 15. In this case, the K did not divide N exactly, so the last group was of size less then K.
If there is a nicer/faster solution which only works if N is a multiple of K, I would also appreciate it. | 2011/09/14 | [
"https://Stackoverflow.com/questions/7420815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/395744/"
] | Try this:
```
library(zoo)
rollapply(v, 3, by = 3, sum, partial = TRUE, align = "left")
## [1] 6 15 15
```
or
```
apply(matrix(c(v, rep(NA, 3 - length(v) %% 3)), 3), 2, sum, na.rm = TRUE)
## [1] 6 15 15
```
Also, in the case of `sum` the last one could be shortened to
```
colSums(matrix(c(v, rep(0, 3 - length(v) %% 3)), 3))
``` | You could try this as well. This works nicely even if you want to include overlapping intervals, as controlled by `by`, and as a bonus, returns the intervals over which each value is derived:
```
library (gtools)
v2 <- running(v, fun=sum, width=3, align="left", allow.fewer=TRUE, by=3)
v2
1:3 4:6 7:8
6 15 15
``` |
7,420,815 | I am looking for a nice and fast way of applying some arbitrary function which operates on vectors, such as `sum`, consecutively to a subvector of consecutive K elements.
Here is one simple example, which should illustrate very clearly what I want:
```
v <- c(1, 2, 3, 4, 5, 6, 7, 8)
v2 <- myapply(v, sum, group_size=3) # v2 should be equal to c(6, 15, 15)
```
The function should try to process groups of `group_size` elements of a given vector and apply a function to each group (treating it as another vector). In this example, the vector `v2` is obtained as follows: (1 + 2 + 3) = 6, (4 + 5 + 6) = 15, (7 + 8) = 15. In this case, the K did not divide N exactly, so the last group was of size less then K.
If there is a nicer/faster solution which only works if N is a multiple of K, I would also appreciate it. | 2011/09/14 | [
"https://Stackoverflow.com/questions/7420815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/395744/"
] | As @Chase said in a comment, you can create your own grouping variable and then use that. Wrapping that process into a function would look like
```
myapply <- function(v, fun, group_size=1) {
unname(tapply(v, (seq_along(v)-1) %/% group_size, fun))
}
```
which gives your results
```
> myapply(v, sum, group_size=3)
[1] 6 15 15
```
Note this does not require the length of `v` to be a multiple of the `group_size`. | You could try this as well. This works nicely even if you want to include overlapping intervals, as controlled by `by`, and as a bonus, returns the intervals over which each value is derived:
```
library (gtools)
v2 <- running(v, fun=sum, width=3, align="left", allow.fewer=TRUE, by=3)
v2
1:3 4:6 7:8
6 15 15
``` |
7,861,398 | well I have a counter of collision between two images (the counter is the score of my game) and I would like to `do something` every time the counter is 1000, or 2000 or 3000 ... every ten thousands.How can I do this please ? | 2011/10/22 | [
"https://Stackoverflow.com/questions/7861398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/956450/"
] | You say 10,000 but you write 1000, here is what I would do for 1000:
```
if (counter % 1000 == 0) {
//Do something.
}
```
For 10,000 do:
```
if (counter % 10000 == 0) {
//Do something.
}
``` | ```
if(counter%1000 == 0) {
//do something
}
``` |
40,990 | In Revelation "kyrios" is used some 21 times e.g. Rev 16v7. It is mostly translated "lord". In the N.K.J.V. in Rev 6v10 a word is also translated "lord" but this time it is "despotes" not "kyrios". Kyrios is well established [21 times] so is there some special significance to the only time that despotes is used in Revelation? | 2019/06/06 | [
"https://hermeneutics.stackexchange.com/questions/40990",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/25763/"
] | Thayer has an interesting comment to make about the difference between the two words :
>
> I Tim 6:1, II Timothy 2:21, Titus 2:9, I Pet 2:18 .... God is thus addressed '*despotes*' by one who calls himself '*doulos*' (a bondman).
>
>
> Christ is called '*despotes*' as one who has bought (sic, I would say 'redeemed) his servants II Peter 2:1.
>
>
> Jude 4 refers to the One (some take it as God) who rules over the church and whose prerogative it is to take vengeance on those who persecute his followers.
>
>
>
Thayer further comments on the correlation between *despotes* and *doulos* in regard to absolute ownership and uncontrolled power. He says that *kurios* had a wider meaning applicable to the various ranks and relations of life, being not suggestive of either property or absolutism.
It seems to me that Thayer is saying that *kurios* is an aspect of personal relationship whilst *despotes* is a matter of rule and power.
Reference : Joseph H Thayer 4th edition 1896. | The word δεσπότης (despotés) occurs about 10 times in the GNT and is used as a title for Jesus/Messiah/God in these places: Luke 2:29 ("Lord's Christ"), Acts 4:24, 2 Tim 2:21, Jude 4, Rev 6:10. In the other instances, it refers to an earthly person such as a slave owner or master of the household. Jude 4 is significant as both despotes and kyrios occur together.
The word kyrios is (as the OP correctly notes) frequently used as title for Jesus but it also used as a title for earthly humans as well.
The meaning of these two words clearly overlaps significantly. BDAG describes δεσπότης (despotés) as meaning:
* **One who has legal control and authority over persons such as subjects or slaves, *lord, master***, or,
* **One who controls a thing, *owner*** of a vessel 2 Tim 2:21.
Thus, δεσπότης (despotés) is an entirely expected title for Jesus.
In the LXX "kyrios" is used to translate the tetragrammaton "YHWH" and so when used as a title for Jesus, carried this extra baggage/connotation of meaning, that is, supreme God. By contrast "despotes" has the meaning of "master". Clearly, the NT depicts Jesus in both these capacities as Jude 4 makes clear. |
55,238,689 | I have a slider and every time I click on one slide I want to get the current active index. Based on the current index I want to set the state, but I keep getting `Maximum update depth exceeded`.
```
state = {
profiles: profileData,
educations: educationData,
selectedProfile: localStorage.getItem('slug'),
selectedEducation: localStorage.getItem('sector') || '',
popupActive: false,
profileSelected: true,
sector: 'Zorg',
showVideo: true,
primaryImg: Timmerman,
redirect: false,
defaultImage: Default,
noSector: Tijdelijk,
slideActive: true,
playState: false,
primaryVid:
'https://localhost.web/videos/desktop/fase2/NPRZ_ADB_Video_2_1_V2.mp4',
thumbIndex: 0,
showTumbs: false,
};
componentDidUpdate() {
if (this.state.slideActive === true) {
console.log('Thumbs showing');
this.setState({
slideActive: false,
});
}
}
// Switch the primary splashscreen and vid src with the image clicked
switchPrimary = e => {
this.setState({
primaryImg: e.target.style.backgroundImage.split(/"/)[1], // get the data so that it can be passed on to the child component
primaryVid: e.target.getAttribute('data'), // get the data so that it can be passed on to the child component
slideActive: true,
thumbIndex: e.currentTarget.getAttribute('data-index'),
playFromThumb: true,
showTumbs: false,
});
// console.log('hiding:', this.state.showTumbs);
// console.log('actief');
// if (this.state.showTumbs === false) {
// this.setState({
// showTumbs: true,
// });
// }
};
``` | 2019/03/19 | [
"https://Stackoverflow.com/questions/55238689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You are checking if `slideActive` in state is true in `componentDidUpdate`, and if it is you call `setState`, which will result in a new call to `componentDidUpdate`, and the loop continues.
You also want to check that `slideActive` actually changed from the previous update.
```
componentDidUpdate(prevProps, prevState) {
if (prevState.slideActive !== this.state.slideActive && this.state.slideActive) {
console.log("Thumbs showing");
this.setState({
slideActive: false
});
}
}
``` | You should put you logic inside `componentDidMount` inside a condition comparing old state to new or old vs new props to avoid it:
>
> You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition, or you’ll cause an infinite loop.
>
>
>
more read and examples: [React ComponentDidUpdate()](https://reactjs.org/docs/react-component.html#componentdidupdate) |
43,890,476 | I work in a company and our app is localizable, but we have encountered a problem.
Original language is PL and we have EN translation in satellite assemblies (\*.resource files translated using Sisulizer).
When we run our app without changing language on english OS, our app is translated to EN in some places and I can't find why.
When we have 'original' PL language it should stay PL and not look for any satellite assemblies to translate itself for OS language. We have CurrentUICulture set to pl-PL but when I run Assembly Binding Log Viewer it shows that one of dll's is looking for \*.resources file with culture=en.
More to say, this dll is Base class dll.
BaseForms is subproject holding all base forms and it's built as dll. This dll is looking for \*.resources in log.
ourAppName is another subproject that is built as exe and it has some forms that derives from BaseForms, f.e. Main Form.
any tips, please? | 2017/05/10 | [
"https://Stackoverflow.com/questions/43890476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7991184/"
] | Store the random String in a local variable and use that in the `p.teleport`. Code would look like this:
```
String randomString = plugin.getRandomStringFromList(plugin.getLocationList());
p.teleport(new Location(Bukkit.getWorld("world"),
plugin.getConfig().getInt("locations." + randomString + ".x"),
plugin.getConfig().getInt("locations." + randomString + ".y"),
plugin.getConfig().getInt("locations." + randomString + ".z")));
``` | This is because you are randomizing "get location" on 3 different instance in the same line
What you could do is that you could save the results of the first instance and reuse it
```
var location = plugin.getRandomStringFromList(plugin.getLocationList());
p.teleport(new Location(Bukkit.getWorld("world"),
plugin.getConfig().getInt("locations." + location + ".x"),
plugin.getConfig().getInt("locations." + location + ".y"),
plugin.getConfig().getInt("locations." + location + ".z")));
``` |
20,211,286 | I've been able to work most of the problems out, but I've encountered a few that I'm uncertain as to how to address.
Let me explain: I have an example file that contains all the non-distinct combinations of the lower case alphabet up to length two (i.e. `aa, ab, ac, ad...`). The total number of non-distinct combinations is therefore 26^2, 676.
Knowing this is quite useful because I know that there are 676 lines, each containing a string of length 2.
Here is the code:
```
#include <stdlib.h>
#include <string.h>
int main(){
FILE* file;
//These would be passed as function arguments
int lines = 676;
int sLength = 2;
int C = lines+1;
int R = sLength+2;
int i,j; //Dummy indices
int len;
//Create 2-D array on the heap
char** mystring = (char**) malloc(C*sizeof(char*));
for(i = 0; i<C; i++) mystring[i] = (char *) malloc(R*sizeof(char)); //Need to free each element individually later on
//Create temporary char array
char line[R];
//Open file to read and store values
file = fopen("alphaLow2.txt", "r");
if(file == NULL) perror("Error opening file");
else{
i = 0;
while(fgets(line, sizeof(line), file) != NULL){
//Remove next line
len = strlen(line);
if((line[len-1]) == '\n') (line[len-1]) = '\0';
len--; //Decrement length by one because of replacing EOL with null terminator
//Copy character set
strcpy(mystring[i], line); //NOT certain if this works being that mystring is 2-D
i++;
}
mystring[C] = '\0'; //Append null terminator
}
for(i = 0; mystring[i]; i++){
for(j = 0; mystring[i][j]; j++){
printf("%c", mystring[i][j]);
}
}
getchar();
return 0;
}
```
To explain further, `int C = lines+1` in order to append a null terminator. `int R = sLength+2` in order to account for the `\n` present in the file, and the fact that `fgets()` always adds a null terminator. Therefore, in this example, the array should be of dimensions `mystring[C][R]` --> `mystring[677][4]`. The while loop replaces the `\n` with `\0`. The printout is correct, but at the very end of the printout, there is an odd string:

The characters after `zz` should not be there. This leaves me to wonder whether there is some memory corruption occurring somewhere in my program. Perhaps my arrays aren't large enough? I'm not sure. Otherwise, everything else appears to be functioning correctly.
Also, I will free the memory in the final program. Right now, I'm trying to get this to work properly. I'm also aware there are much easier ways to do this. For instance, `std::string array` would make this much easier. However, I'm am copying this array to a cuda enabled device, and cuda does not recognize that form.
Any constructive input is appreciated. | 2013/11/26 | [
"https://Stackoverflow.com/questions/20211286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599549/"
] | Just reposition ur UL outside foreach
```
function GenerateNavHTML($rows ,$count=5)
{
$html = '';
$html .= '<div><ul>';
$ctr = 0;
foreach($rows as $key =>$value)
{
if(!$ctr)
$html .= "<ul>";
$html .='<li>';
$html .= '<a href="' . $value['title'] . '">' . $value['title'] . '</a>';
$html .= '</li>';
$ctr++;
if($ctr == $count)
{
$html .= "</ul>";
$ctr = 0;
}
}
if($ctr > $count)
$html .= '</ul>';
$html .= '</div>';
return $html;
}
``` | If I understand you correctly, this should do it:
```
foreach($rows as $key =>$value){
if(count($rows) > $count){
$html .= '<ul>';
}
$html .='<li>';
$html .= '<a href="' . $value['title'] . '">' . $value['title'] . '</a>';
$html .= '</li>';
if(count($rows) > $count){
$html .= '</ul>';
}
}
``` |
20,211,286 | I've been able to work most of the problems out, but I've encountered a few that I'm uncertain as to how to address.
Let me explain: I have an example file that contains all the non-distinct combinations of the lower case alphabet up to length two (i.e. `aa, ab, ac, ad...`). The total number of non-distinct combinations is therefore 26^2, 676.
Knowing this is quite useful because I know that there are 676 lines, each containing a string of length 2.
Here is the code:
```
#include <stdlib.h>
#include <string.h>
int main(){
FILE* file;
//These would be passed as function arguments
int lines = 676;
int sLength = 2;
int C = lines+1;
int R = sLength+2;
int i,j; //Dummy indices
int len;
//Create 2-D array on the heap
char** mystring = (char**) malloc(C*sizeof(char*));
for(i = 0; i<C; i++) mystring[i] = (char *) malloc(R*sizeof(char)); //Need to free each element individually later on
//Create temporary char array
char line[R];
//Open file to read and store values
file = fopen("alphaLow2.txt", "r");
if(file == NULL) perror("Error opening file");
else{
i = 0;
while(fgets(line, sizeof(line), file) != NULL){
//Remove next line
len = strlen(line);
if((line[len-1]) == '\n') (line[len-1]) = '\0';
len--; //Decrement length by one because of replacing EOL with null terminator
//Copy character set
strcpy(mystring[i], line); //NOT certain if this works being that mystring is 2-D
i++;
}
mystring[C] = '\0'; //Append null terminator
}
for(i = 0; mystring[i]; i++){
for(j = 0; mystring[i][j]; j++){
printf("%c", mystring[i][j]);
}
}
getchar();
return 0;
}
```
To explain further, `int C = lines+1` in order to append a null terminator. `int R = sLength+2` in order to account for the `\n` present in the file, and the fact that `fgets()` always adds a null terminator. Therefore, in this example, the array should be of dimensions `mystring[C][R]` --> `mystring[677][4]`. The while loop replaces the `\n` with `\0`. The printout is correct, but at the very end of the printout, there is an odd string:

The characters after `zz` should not be there. This leaves me to wonder whether there is some memory corruption occurring somewhere in my program. Perhaps my arrays aren't large enough? I'm not sure. Otherwise, everything else appears to be functioning correctly.
Also, I will free the memory in the final program. Right now, I'm trying to get this to work properly. I'm also aware there are much easier ways to do this. For instance, `std::string array` would make this much easier. However, I'm am copying this array to a cuda enabled device, and cuda does not recognize that form.
Any constructive input is appreciated. | 2013/11/26 | [
"https://Stackoverflow.com/questions/20211286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599549/"
] | Just reposition ur UL outside foreach
```
function GenerateNavHTML($rows ,$count=5)
{
$html = '';
$html .= '<div><ul>';
$ctr = 0;
foreach($rows as $key =>$value)
{
if(!$ctr)
$html .= "<ul>";
$html .='<li>';
$html .= '<a href="' . $value['title'] . '">' . $value['title'] . '</a>';
$html .= '</li>';
$ctr++;
if($ctr == $count)
{
$html .= "</ul>";
$ctr = 0;
}
}
if($ctr > $count)
$html .= '</ul>';
$html .= '</div>';
return $html;
}
``` | Just move the parts you don´t want to be repeated to outside the foreach-loop, i.e.
```
function GenerateNavHTML($rows ,$count=5)
{
$html .= '<div><ul>';
...
```
while inside the loop you start right with the `<li>...</li>` |
34,350,527 | I'm building a form that should support entering attributes for multiple instances of the same product. To allow a user to create an arbitrary number of instances I'm using `ng-repeat` and building an additional version of the form when an "add version" button is clicked. For static inputs this works as expected as a new form is created and the entered values are not linked between instances. However, I'm also intending to support a dynamic list of individual attributes using `ng-repeat` and in my current implementation the `addVersion()` function is copying both the number of attributes and the values within.
I've read [several](https://stackoverflow.com/questions/26742361/angularjs-ng-repeat-track-by-index-inside-nested-loops) [questions](https://stackoverflow.com/questions/15256600/passing-2-index-values-within-nested-ng-repeat) on this topic and it's clear to me I should be using `$index` but I'm afraid I'm new enough to Angular that I can't totally get my head around how to do this.
EDIT: [Here's a working example that should highlight the problem](http://plnkr.co/edit/Vqy0ppKVsYxqATTc3ffm?p=preview)
For the purpose of clarity I'm hoping to be able to generate a response that looks like:
>
> Product Name: A Car
>
> Product Description: You can sit in it and also drive it
>
> *Version 1*
>
> Price: $500
>
> Quantity: 3
>
> Features: 1) Goes fast 2) is red
>
> *Version 2*
>
> Price: $600
>
> Quantity: 4
>
> Features: 1) Goes really fast 2) is blue 3) has windshield wipers
>
>
>
But instead I'm seeing the values in features cloned... which makes sense because I'm clearly pushing them to the same array I just don't know how to change that :)
Right now a simplified version of the code looks like this:
**HTML**:
```
<form>
<input type="text" ng-model="name" placeholder="Product Name">
<textarea ng-model="description" placeholder="Product Description"></textarea>
<button ng-click="addVersion()">Add Version</button>
<!-- Additional feature inputs should be exclusive to each instance and not replicated across all -->
<div ng-repeat="version in versions">
<input type="number" ng-model="instance.price" placeholder="Price">
<input type="number" ng-model="instance.quantity" placeholder="Quantity">
<button ng-click="addInput()">Add Feature</button>
<fieldset ng-repeat="feature in features">
<input type="text" ng-model="instance.feature.name" placeholder="feature">
</fieldset>
</div>
</form>
```
**JS**:
```
$scope.versions = [{}];
$scope.addVersion = function() {
$scope.versions.push({});
};
$scope.features = [];
$scope.addInput = function() {
$scope.features.push({});
};
```
I think the solution here is stupidly obvious I'm just a bit lost. Thanks! | 2015/12/18 | [
"https://Stackoverflow.com/questions/34350527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1888712/"
] | I think you'll be able to fix the issue as shown below. Key change is that, youshould pass the `version` object to the `addInput` method and add feature to that instance.
I strongly suggest creating a directive for this task.
```js
angular.module('Form', []).controller('multipleVersions', function($scope) {
$scope.versions = [{
features: [{
features: [{}]
}]
}];
$scope.addVersion = function() {
$scope.versions.push({
features: [{}]
});
};
$scope.addInput = function(version) {
version.features.push({});
};
$scope.removeInput = function(version, index) {
version.features.splice(index, 1);
};
});
```
```css
input {
display: block;
}
#addVersionButton {
display: block;
}
.version {
margin-top: 20px;
border: 1px solid black;
}
.feature {
display: inline;
}
.removeInput {
display: inline;
}
fieldset {
border: 0;
padding: 0;
margin: 0;
min-width: 0;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<form ng-app="Form" ng-controller="multipleVersions">
<input type="text" ng-model="product.name" placeholder="Product Name">
<textarea ng-model="product.description" placeholder="Product Description"></textarea>
<button id="addVersionButton" ng-click="addVersion()">Add Version</button>
<div class="version" ng-repeat="version in versions">
<input type="number" ng-model="version.price" placeholder="Price">
<input type="number" ng-model="version.quantity" placeholder="Quantity">
<button ng-click="addInput(version)">Add Feature</button>
<fieldset ng-repeat="feature in version.features">
<input class="feature" type="text" ng-model="feature.name" placeholder="feature">
<button class="removeInput" ng-click="removeInput(version,$index)">-</button>
</fieldset>
</div>
</form>
``` | I think you're just overrating the variable instance...
When you working with ng-repeat, Its recommendable to you work with the repeater variable...
Can you try this?
```
<form>
<input type="text" ng-model="name" placeholder="Product Name">
<textarea ng-model="description" placeholder="Product Description"></textarea>
<button ng-click="addVersion()">Add Version</button>
<!-- Additional feature inputs should be exclusive to each instance and not replicated across all -->
<div ng-repeat="version in versions">
<input type="number" ng-model="version.instance.price" placeholder="Price">
<input type="number" ng-model="version.instance.quantity" placeholder="Quantity">
<button ng-click="addInput()">Add Feature</button>
<fieldset ng-repeat="feature in features">
<input type="text" ng-model="version.instance.feature.name" placeholder="feature">
</fieldset>
</div>
</form>
```
In repeat of features, I guess its wrong. I suggest you to add features to version.instance to it before.
Tip: If you testing it with chrome browser, press f12 and see the 'Console' log. If you accessing some property of null variable (my guess) you'll get an NullException error. |
34,350,527 | I'm building a form that should support entering attributes for multiple instances of the same product. To allow a user to create an arbitrary number of instances I'm using `ng-repeat` and building an additional version of the form when an "add version" button is clicked. For static inputs this works as expected as a new form is created and the entered values are not linked between instances. However, I'm also intending to support a dynamic list of individual attributes using `ng-repeat` and in my current implementation the `addVersion()` function is copying both the number of attributes and the values within.
I've read [several](https://stackoverflow.com/questions/26742361/angularjs-ng-repeat-track-by-index-inside-nested-loops) [questions](https://stackoverflow.com/questions/15256600/passing-2-index-values-within-nested-ng-repeat) on this topic and it's clear to me I should be using `$index` but I'm afraid I'm new enough to Angular that I can't totally get my head around how to do this.
EDIT: [Here's a working example that should highlight the problem](http://plnkr.co/edit/Vqy0ppKVsYxqATTc3ffm?p=preview)
For the purpose of clarity I'm hoping to be able to generate a response that looks like:
>
> Product Name: A Car
>
> Product Description: You can sit in it and also drive it
>
> *Version 1*
>
> Price: $500
>
> Quantity: 3
>
> Features: 1) Goes fast 2) is red
>
> *Version 2*
>
> Price: $600
>
> Quantity: 4
>
> Features: 1) Goes really fast 2) is blue 3) has windshield wipers
>
>
>
But instead I'm seeing the values in features cloned... which makes sense because I'm clearly pushing them to the same array I just don't know how to change that :)
Right now a simplified version of the code looks like this:
**HTML**:
```
<form>
<input type="text" ng-model="name" placeholder="Product Name">
<textarea ng-model="description" placeholder="Product Description"></textarea>
<button ng-click="addVersion()">Add Version</button>
<!-- Additional feature inputs should be exclusive to each instance and not replicated across all -->
<div ng-repeat="version in versions">
<input type="number" ng-model="instance.price" placeholder="Price">
<input type="number" ng-model="instance.quantity" placeholder="Quantity">
<button ng-click="addInput()">Add Feature</button>
<fieldset ng-repeat="feature in features">
<input type="text" ng-model="instance.feature.name" placeholder="feature">
</fieldset>
</div>
</form>
```
**JS**:
```
$scope.versions = [{}];
$scope.addVersion = function() {
$scope.versions.push({});
};
$scope.features = [];
$scope.addInput = function() {
$scope.features.push({});
};
```
I think the solution here is stupidly obvious I'm just a bit lost. Thanks! | 2015/12/18 | [
"https://Stackoverflow.com/questions/34350527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1888712/"
] | I think you'll be able to fix the issue as shown below. Key change is that, youshould pass the `version` object to the `addInput` method and add feature to that instance.
I strongly suggest creating a directive for this task.
```js
angular.module('Form', []).controller('multipleVersions', function($scope) {
$scope.versions = [{
features: [{
features: [{}]
}]
}];
$scope.addVersion = function() {
$scope.versions.push({
features: [{}]
});
};
$scope.addInput = function(version) {
version.features.push({});
};
$scope.removeInput = function(version, index) {
version.features.splice(index, 1);
};
});
```
```css
input {
display: block;
}
#addVersionButton {
display: block;
}
.version {
margin-top: 20px;
border: 1px solid black;
}
.feature {
display: inline;
}
.removeInput {
display: inline;
}
fieldset {
border: 0;
padding: 0;
margin: 0;
min-width: 0;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<form ng-app="Form" ng-controller="multipleVersions">
<input type="text" ng-model="product.name" placeholder="Product Name">
<textarea ng-model="product.description" placeholder="Product Description"></textarea>
<button id="addVersionButton" ng-click="addVersion()">Add Version</button>
<div class="version" ng-repeat="version in versions">
<input type="number" ng-model="version.price" placeholder="Price">
<input type="number" ng-model="version.quantity" placeholder="Quantity">
<button ng-click="addInput(version)">Add Feature</button>
<fieldset ng-repeat="feature in version.features">
<input class="feature" type="text" ng-model="feature.name" placeholder="feature">
<button class="removeInput" ng-click="removeInput(version,$index)">-</button>
</fieldset>
</div>
</form>
``` | Thanks to everyone who helped. None of the solutions suggested covered everything however they definitely pushed me to the answer. Separate questions and solutions broken out below and a working version of the original <http://plnkr.co/edit/T74bfNXxpYs16ENNUEjv?p=preview>:
Duplication Of Dynamically Added Inputs: This was handled by passing `version` to the `addInput()` method and modifying the js to properly had the arrays:
```
$scope.versions = [{
features: [{
features: [{}]
}]
}];
$scope.addVersion = function() {
$scope.versions.push({
features: [{}]
});
};
$scope.addInput = function(version) {
version.features.push({});
};
```
Thanks to [T J](https://stackoverflow.com/users/2333214/t-j) for the solution in one of the answers below. This allowed individual inputs to be created but the text was cloned across all of them and the delete button no longer worked.
Cloned Text: Every group of inputs was writing to the same model at `version.feature.name`. Following the solution [here](https://stackoverflow.com/questions/13714884/difficulty-with-ng-model-ng-repeat-and-inputs) and tracking by $index solved that.
Remove Buttons: The `removeInput()` method was no longer referencing the specific input it was paired with and required that I pass in both the `$parent.$index` (to reference the version) and the `$index` (to reference the specific input.)
Final code below:
HTML:
```
<form>
<input type="text" ng-model="name" placeholder="Product Name">
<textarea ng-model="description" placeholder="Product Description"></textarea>
<button id="addVersionButton" ng-click="addVersion()">Add Version</button>
<div class="version" ng-repeat="version in versions">
<span>Instance {{$index}}</span>
<input type="number" ng-model="version.price" placeholder="Price">
<input type="number" ng-model="version.quantity" placeholder="Quantity">
<button ng-click="addInput(version)">Add Feature</button>
<fieldset ng-repeat="feature in version.features">
<!-- Additional feature inputs should be exclusive to each instance and not replicated across all -->
<input class="feature" type="text" ng-model="version.features[$index].value" placeholder="feature">
<button class="removeInput" ng-click="removeInput($parent.$index, $index)">-</button>
</fieldset>
</div>
</form>
```
JS
```
$scope.versions = [{}];
$scope.addVersion = function() {
$scope.versions.push({});
};
$scope.features = [];
$scope.addInput = function() {
$scope.features.push({});
};
$scope.removeInput = function(index) {
$scope.features.splice(index, 1);
};
``` |
34,350,527 | I'm building a form that should support entering attributes for multiple instances of the same product. To allow a user to create an arbitrary number of instances I'm using `ng-repeat` and building an additional version of the form when an "add version" button is clicked. For static inputs this works as expected as a new form is created and the entered values are not linked between instances. However, I'm also intending to support a dynamic list of individual attributes using `ng-repeat` and in my current implementation the `addVersion()` function is copying both the number of attributes and the values within.
I've read [several](https://stackoverflow.com/questions/26742361/angularjs-ng-repeat-track-by-index-inside-nested-loops) [questions](https://stackoverflow.com/questions/15256600/passing-2-index-values-within-nested-ng-repeat) on this topic and it's clear to me I should be using `$index` but I'm afraid I'm new enough to Angular that I can't totally get my head around how to do this.
EDIT: [Here's a working example that should highlight the problem](http://plnkr.co/edit/Vqy0ppKVsYxqATTc3ffm?p=preview)
For the purpose of clarity I'm hoping to be able to generate a response that looks like:
>
> Product Name: A Car
>
> Product Description: You can sit in it and also drive it
>
> *Version 1*
>
> Price: $500
>
> Quantity: 3
>
> Features: 1) Goes fast 2) is red
>
> *Version 2*
>
> Price: $600
>
> Quantity: 4
>
> Features: 1) Goes really fast 2) is blue 3) has windshield wipers
>
>
>
But instead I'm seeing the values in features cloned... which makes sense because I'm clearly pushing them to the same array I just don't know how to change that :)
Right now a simplified version of the code looks like this:
**HTML**:
```
<form>
<input type="text" ng-model="name" placeholder="Product Name">
<textarea ng-model="description" placeholder="Product Description"></textarea>
<button ng-click="addVersion()">Add Version</button>
<!-- Additional feature inputs should be exclusive to each instance and not replicated across all -->
<div ng-repeat="version in versions">
<input type="number" ng-model="instance.price" placeholder="Price">
<input type="number" ng-model="instance.quantity" placeholder="Quantity">
<button ng-click="addInput()">Add Feature</button>
<fieldset ng-repeat="feature in features">
<input type="text" ng-model="instance.feature.name" placeholder="feature">
</fieldset>
</div>
</form>
```
**JS**:
```
$scope.versions = [{}];
$scope.addVersion = function() {
$scope.versions.push({});
};
$scope.features = [];
$scope.addInput = function() {
$scope.features.push({});
};
```
I think the solution here is stupidly obvious I'm just a bit lost. Thanks! | 2015/12/18 | [
"https://Stackoverflow.com/questions/34350527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1888712/"
] | I think you're just overrating the variable instance...
When you working with ng-repeat, Its recommendable to you work with the repeater variable...
Can you try this?
```
<form>
<input type="text" ng-model="name" placeholder="Product Name">
<textarea ng-model="description" placeholder="Product Description"></textarea>
<button ng-click="addVersion()">Add Version</button>
<!-- Additional feature inputs should be exclusive to each instance and not replicated across all -->
<div ng-repeat="version in versions">
<input type="number" ng-model="version.instance.price" placeholder="Price">
<input type="number" ng-model="version.instance.quantity" placeholder="Quantity">
<button ng-click="addInput()">Add Feature</button>
<fieldset ng-repeat="feature in features">
<input type="text" ng-model="version.instance.feature.name" placeholder="feature">
</fieldset>
</div>
</form>
```
In repeat of features, I guess its wrong. I suggest you to add features to version.instance to it before.
Tip: If you testing it with chrome browser, press f12 and see the 'Console' log. If you accessing some property of null variable (my guess) you'll get an NullException error. | Thanks to everyone who helped. None of the solutions suggested covered everything however they definitely pushed me to the answer. Separate questions and solutions broken out below and a working version of the original <http://plnkr.co/edit/T74bfNXxpYs16ENNUEjv?p=preview>:
Duplication Of Dynamically Added Inputs: This was handled by passing `version` to the `addInput()` method and modifying the js to properly had the arrays:
```
$scope.versions = [{
features: [{
features: [{}]
}]
}];
$scope.addVersion = function() {
$scope.versions.push({
features: [{}]
});
};
$scope.addInput = function(version) {
version.features.push({});
};
```
Thanks to [T J](https://stackoverflow.com/users/2333214/t-j) for the solution in one of the answers below. This allowed individual inputs to be created but the text was cloned across all of them and the delete button no longer worked.
Cloned Text: Every group of inputs was writing to the same model at `version.feature.name`. Following the solution [here](https://stackoverflow.com/questions/13714884/difficulty-with-ng-model-ng-repeat-and-inputs) and tracking by $index solved that.
Remove Buttons: The `removeInput()` method was no longer referencing the specific input it was paired with and required that I pass in both the `$parent.$index` (to reference the version) and the `$index` (to reference the specific input.)
Final code below:
HTML:
```
<form>
<input type="text" ng-model="name" placeholder="Product Name">
<textarea ng-model="description" placeholder="Product Description"></textarea>
<button id="addVersionButton" ng-click="addVersion()">Add Version</button>
<div class="version" ng-repeat="version in versions">
<span>Instance {{$index}}</span>
<input type="number" ng-model="version.price" placeholder="Price">
<input type="number" ng-model="version.quantity" placeholder="Quantity">
<button ng-click="addInput(version)">Add Feature</button>
<fieldset ng-repeat="feature in version.features">
<!-- Additional feature inputs should be exclusive to each instance and not replicated across all -->
<input class="feature" type="text" ng-model="version.features[$index].value" placeholder="feature">
<button class="removeInput" ng-click="removeInput($parent.$index, $index)">-</button>
</fieldset>
</div>
</form>
```
JS
```
$scope.versions = [{}];
$scope.addVersion = function() {
$scope.versions.push({});
};
$scope.features = [];
$scope.addInput = function() {
$scope.features.push({});
};
$scope.removeInput = function(index) {
$scope.features.splice(index, 1);
};
``` |
2,118,972 | Is there a LaTeX command that prints the "last modified" date of the actual document? Since LaTeX projects consist of more than one file this command ideally prints the date of the actual file, not that of the project. | 2010/01/22 | [
"https://Stackoverflow.com/questions/2118972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46428/"
] | Unfortunately, TeX does not provide commands for such information; the only way to get such information is
1. by running a non-TeX script to create a TeX file *before* running LaTeX and including this file in your main LaTeX document somehow, or
2. by running the external script *from* TeX (which only works if the so-called write18 or shellescape feature is enabled; you'd have to consult the manual of your TeX implementation for this, and not have a stubborn sysadmin).
It is possible that extended TeXs do support file info commands (luaTeX perhaps?), but it's not part of TeX proper. | thank dmckee
```
LATEX_SRCS = test.tex
define moddate
date +%Y%m%d%H%M%S
endef
today.sty: $(LATEX_SRCS)
@echo "\def\moddate{"$(shell $(moddate))"}"> $@
``` |
2,118,972 | Is there a LaTeX command that prints the "last modified" date of the actual document? Since LaTeX projects consist of more than one file this command ideally prints the date of the actual file, not that of the project. | 2010/01/22 | [
"https://Stackoverflow.com/questions/2118972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46428/"
] | The package [filemod](http://www.ctan.org/tex-archive/macros/latex/contrib/filemod) seems to do exactly what you need. To get the last modified date of the file you just include the package in the usual way:
```
\usepackage{filemod}
```
and the modification time of the current document is printed by:
```
\filemodprintdate{\jobname}
```
you can also print the modification time, and there are many options to format the output. | thank dmckee
```
LATEX_SRCS = test.tex
define moddate
date +%Y%m%d%H%M%S
endef
today.sty: $(LATEX_SRCS)
@echo "\def\moddate{"$(shell $(moddate))"}"> $@
``` |
2,118,972 | Is there a LaTeX command that prints the "last modified" date of the actual document? Since LaTeX projects consist of more than one file this command ideally prints the date of the actual file, not that of the project. | 2010/01/22 | [
"https://Stackoverflow.com/questions/2118972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46428/"
] | Unfortunately, TeX does not provide commands for such information; the only way to get such information is
1. by running a non-TeX script to create a TeX file *before* running LaTeX and including this file in your main LaTeX document somehow, or
2. by running the external script *from* TeX (which only works if the so-called write18 or shellescape feature is enabled; you'd have to consult the manual of your TeX implementation for this, and not have a stubborn sysadmin).
It is possible that extended TeXs do support file info commands (luaTeX perhaps?), but it's not part of TeX proper. | If you are using an automated build system, you could ask it to generate a file (perhaps named `today.sty`) which depends on all the source files.
In make that might look like:
```
today.sty: $LATEX_SRCS
echo "\date{" > $@
date +D >> $@
echo "}" >> $@
```
and `\usepackage{today.sty}`.
The will use the date of the *first* build after a file changes, and won't update until either you delete `today.sty` or alter another source file. |
2,118,972 | Is there a LaTeX command that prints the "last modified" date of the actual document? Since LaTeX projects consist of more than one file this command ideally prints the date of the actual file, not that of the project. | 2010/01/22 | [
"https://Stackoverflow.com/questions/2118972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46428/"
] | pdfTeX provides the primitive `\pdffilemoddate` to query this information for files. (LuaTeX uses its own Lua functions for the same thing.) Since pdfTeX is used by default in all LaTeX distributions in the last few years (at least), there's no harm in using the new functionality unless you're dealing with very old production systems. Here's an example:
```
\documentclass{article}
\begin{document}
\def\parsedate #1:20#2#3#4#5#6#7#8\empty{20#2#3/#4#5/#6#7}
\def\moddate#1{\expandafter\parsedate\pdffilemoddate{#1}\empty}
this is the moddate: \moddate{\jobname.tex}
\end{document}
```
(Assuming the file has been modified since year 2000.) | If you are using an automated build system, you could ask it to generate a file (perhaps named `today.sty`) which depends on all the source files.
In make that might look like:
```
today.sty: $LATEX_SRCS
echo "\date{" > $@
date +D >> $@
echo "}" >> $@
```
and `\usepackage{today.sty}`.
The will use the date of the *first* build after a file changes, and won't update until either you delete `today.sty` or alter another source file. |
2,118,972 | Is there a LaTeX command that prints the "last modified" date of the actual document? Since LaTeX projects consist of more than one file this command ideally prints the date of the actual file, not that of the project. | 2010/01/22 | [
"https://Stackoverflow.com/questions/2118972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46428/"
] | The package [filemod](http://www.ctan.org/tex-archive/macros/latex/contrib/filemod) seems to do exactly what you need. To get the last modified date of the file you just include the package in the usual way:
```
\usepackage{filemod}
```
and the modification time of the current document is printed by:
```
\filemodprintdate{\jobname}
```
you can also print the modification time, and there are many options to format the output. | If you are using an automated build system, you could ask it to generate a file (perhaps named `today.sty`) which depends on all the source files.
In make that might look like:
```
today.sty: $LATEX_SRCS
echo "\date{" > $@
date +D >> $@
echo "}" >> $@
```
and `\usepackage{today.sty}`.
The will use the date of the *first* build after a file changes, and won't update until either you delete `today.sty` or alter another source file. |
2,118,972 | Is there a LaTeX command that prints the "last modified" date of the actual document? Since LaTeX projects consist of more than one file this command ideally prints the date of the actual file, not that of the project. | 2010/01/22 | [
"https://Stackoverflow.com/questions/2118972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46428/"
] | The package [filemod](http://www.ctan.org/tex-archive/macros/latex/contrib/filemod) seems to do exactly what you need. To get the last modified date of the file you just include the package in the usual way:
```
\usepackage{filemod}
```
and the modification time of the current document is printed by:
```
\filemodprintdate{\jobname}
```
you can also print the modification time, and there are many options to format the output. | There is the [getfiledate](http://tug.ctan.org/tex-archive/macros/latex/contrib/getfiledate/) LaTeX package (it was part of my LaTeX distribution by default). It seems to be designed to automatically output a paragraph like:
```
The date of last modification of file misc-test1.tex was 2009-10-11 21:45:50.
```
with a bit of ability to tweak the output. You can definitely get just the date. However, I couldn't figure out how to get rid of newlines around the date and how to change the date format. To be honest I think the authors implemented it exactly for the single purpose they needed it, and it is rather cumbersome for general use. |
2,118,972 | Is there a LaTeX command that prints the "last modified" date of the actual document? Since LaTeX projects consist of more than one file this command ideally prints the date of the actual file, not that of the project. | 2010/01/22 | [
"https://Stackoverflow.com/questions/2118972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46428/"
] | If you are using an automated build system, you could ask it to generate a file (perhaps named `today.sty`) which depends on all the source files.
In make that might look like:
```
today.sty: $LATEX_SRCS
echo "\date{" > $@
date +D >> $@
echo "}" >> $@
```
and `\usepackage{today.sty}`.
The will use the date of the *first* build after a file changes, and won't update until either you delete `today.sty` or alter another source file. | There is the [getfiledate](http://tug.ctan.org/tex-archive/macros/latex/contrib/getfiledate/) LaTeX package (it was part of my LaTeX distribution by default). It seems to be designed to automatically output a paragraph like:
```
The date of last modification of file misc-test1.tex was 2009-10-11 21:45:50.
```
with a bit of ability to tweak the output. You can definitely get just the date. However, I couldn't figure out how to get rid of newlines around the date and how to change the date format. To be honest I think the authors implemented it exactly for the single purpose they needed it, and it is rather cumbersome for general use. |
2,118,972 | Is there a LaTeX command that prints the "last modified" date of the actual document? Since LaTeX projects consist of more than one file this command ideally prints the date of the actual file, not that of the project. | 2010/01/22 | [
"https://Stackoverflow.com/questions/2118972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46428/"
] | pdfTeX provides the primitive `\pdffilemoddate` to query this information for files. (LuaTeX uses its own Lua functions for the same thing.) Since pdfTeX is used by default in all LaTeX distributions in the last few years (at least), there's no harm in using the new functionality unless you're dealing with very old production systems. Here's an example:
```
\documentclass{article}
\begin{document}
\def\parsedate #1:20#2#3#4#5#6#7#8\empty{20#2#3/#4#5/#6#7}
\def\moddate#1{\expandafter\parsedate\pdffilemoddate{#1}\empty}
this is the moddate: \moddate{\jobname.tex}
\end{document}
```
(Assuming the file has been modified since year 2000.) | thank dmckee
```
LATEX_SRCS = test.tex
define moddate
date +%Y%m%d%H%M%S
endef
today.sty: $(LATEX_SRCS)
@echo "\def\moddate{"$(shell $(moddate))"}"> $@
``` |
2,118,972 | Is there a LaTeX command that prints the "last modified" date of the actual document? Since LaTeX projects consist of more than one file this command ideally prints the date of the actual file, not that of the project. | 2010/01/22 | [
"https://Stackoverflow.com/questions/2118972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46428/"
] | pdfTeX provides the primitive `\pdffilemoddate` to query this information for files. (LuaTeX uses its own Lua functions for the same thing.) Since pdfTeX is used by default in all LaTeX distributions in the last few years (at least), there's no harm in using the new functionality unless you're dealing with very old production systems. Here's an example:
```
\documentclass{article}
\begin{document}
\def\parsedate #1:20#2#3#4#5#6#7#8\empty{20#2#3/#4#5/#6#7}
\def\moddate#1{\expandafter\parsedate\pdffilemoddate{#1}\empty}
this is the moddate: \moddate{\jobname.tex}
\end{document}
```
(Assuming the file has been modified since year 2000.) | There is the [getfiledate](http://tug.ctan.org/tex-archive/macros/latex/contrib/getfiledate/) LaTeX package (it was part of my LaTeX distribution by default). It seems to be designed to automatically output a paragraph like:
```
The date of last modification of file misc-test1.tex was 2009-10-11 21:45:50.
```
with a bit of ability to tweak the output. You can definitely get just the date. However, I couldn't figure out how to get rid of newlines around the date and how to change the date format. To be honest I think the authors implemented it exactly for the single purpose they needed it, and it is rather cumbersome for general use. |
2,118,972 | Is there a LaTeX command that prints the "last modified" date of the actual document? Since LaTeX projects consist of more than one file this command ideally prints the date of the actual file, not that of the project. | 2010/01/22 | [
"https://Stackoverflow.com/questions/2118972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46428/"
] | If you are using an automated build system, you could ask it to generate a file (perhaps named `today.sty`) which depends on all the source files.
In make that might look like:
```
today.sty: $LATEX_SRCS
echo "\date{" > $@
date +D >> $@
echo "}" >> $@
```
and `\usepackage{today.sty}`.
The will use the date of the *first* build after a file changes, and won't update until either you delete `today.sty` or alter another source file. | thank dmckee
```
LATEX_SRCS = test.tex
define moddate
date +%Y%m%d%H%M%S
endef
today.sty: $(LATEX_SRCS)
@echo "\def\moddate{"$(shell $(moddate))"}"> $@
``` |
70,886,556 | I have two dataframes in the following form:
df1
| id | name | df2\_id |
| --- | --- | --- |
| one | foo | template\_x |
| two | bar | template\_y |
| three | baz | template\_z |
df2
| id | name | value |
| --- | --- | --- |
| template\_x | aaa | zzz |
| template\_x | bbb | yyy |
| template\_y | ccc | xxx |
| template\_y | ddd | www |
| template\_z | eee | vvv |
| template\_z | fff | uuu |
For each value in `df1` where `df2_id` == `df2.id`, I'd like to iterate over `df2` and append the value of `df1.id` to `name` and `value` in each row to get:
df3
| id | concat\_name | concat\_val |
| --- | --- | --- |
| template\_x | aaa\_one | zzz\_one |
| template\_x | bbb\_one | yyy\_one |
| template\_y | ccc\_two | xxx\_two |
| template\_y | ddd\_two | www\_two |
| template\_z | eee\_three | vvv\_three |
| template\_z | fff\_three | uuu\_three |
Constraints/caveats:
* All relevant values are strings, no integers.
* Sometimes `df2.value` is empty, and I would like to keep it empty.
My approach was to use nested for loop with `df.iterrows`, but it's giving me trouble. | 2022/01/27 | [
"https://Stackoverflow.com/questions/70886556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15936178/"
] | You may want to investigate redux form and/or `connect()`
Example:
```
import React from 'react';
import { useForm } from 'react-hook-form';
import { connect } from 'react-redux';
const Form = ({ register, handleSubmit }) => {
const methods = useForm();
return (
<form onSubmit={handleSubmit(register)}>...</form>
);
};
const mapDispatchToProps = dispatch => ({
register: (data) => dispatch(register(data))
});
export default connect(null, mapDispatchToProps)(Form);
import React from 'react';
import { useForm } from 'react-hook-form';
import { connect } from 'react-redux';
const Form = ({ register, handleSubmit }) => {
const methods = useForm();
return (
<form onSubmit={handleSubmit(register)}>...</form>
);
};
export default connect(null, mapDispatchToProps)(Form);
``` | ```
function handleForm(e) {
e.preventDefault()
// your code here
}
<button onClick={()=>{document.forms[0].submit()}} >Submit</button>
<form onSubmit={handleForm} >...</form>
```
For haters who dislike the answer:
```
const formRef=useRef();
function handleForm(e) {
e.preventDefault()
// your code here
}
<button onClick={()=>formRef.current.submit()} >Submit</button>
<form ref={formRef} onSubmit={handleForm} >...</form>
``` |
70,886,556 | I have two dataframes in the following form:
df1
| id | name | df2\_id |
| --- | --- | --- |
| one | foo | template\_x |
| two | bar | template\_y |
| three | baz | template\_z |
df2
| id | name | value |
| --- | --- | --- |
| template\_x | aaa | zzz |
| template\_x | bbb | yyy |
| template\_y | ccc | xxx |
| template\_y | ddd | www |
| template\_z | eee | vvv |
| template\_z | fff | uuu |
For each value in `df1` where `df2_id` == `df2.id`, I'd like to iterate over `df2` and append the value of `df1.id` to `name` and `value` in each row to get:
df3
| id | concat\_name | concat\_val |
| --- | --- | --- |
| template\_x | aaa\_one | zzz\_one |
| template\_x | bbb\_one | yyy\_one |
| template\_y | ccc\_two | xxx\_two |
| template\_y | ddd\_two | www\_two |
| template\_z | eee\_three | vvv\_three |
| template\_z | fff\_three | uuu\_three |
Constraints/caveats:
* All relevant values are strings, no integers.
* Sometimes `df2.value` is empty, and I would like to keep it empty.
My approach was to use nested for loop with `df.iterrows`, but it's giving me trouble. | 2022/01/27 | [
"https://Stackoverflow.com/questions/70886556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15936178/"
] | Just create a ref in the parent component, send it to the child component and assign that ref to an invisible submit button.
Finally, in the onClick event of the parent submit button simply call submitRef.current.click()
```
// ./From.js
import React from 'react';
import { useForm } from 'react-hook-form';
// This is the child component with a ref received from the parent
// and assigned to an invisible submit button
const Form = ({ submitRef }) => {
const {register, setValue, getValues, ...other } = useForm();
return (
<form onSubmit={handleSubmit(onSubmit)}>
...
<button ref={submitRef} type="submit" style={{ display: 'none' }} />
</form>
);
};
export default Form;
```
```
// ./Parent.js
import React, { useRef } from 'react';
import Form from './Form'
const Parent = () => {
const submitRef = useRef();
return (
<>
<button onClick={() => submitRef.current.click()}>Submit</button>
<Form submitRef={submitRef}/>
</>
);
};
export default Parent;
``` | You may want to investigate redux form and/or `connect()`
Example:
```
import React from 'react';
import { useForm } from 'react-hook-form';
import { connect } from 'react-redux';
const Form = ({ register, handleSubmit }) => {
const methods = useForm();
return (
<form onSubmit={handleSubmit(register)}>...</form>
);
};
const mapDispatchToProps = dispatch => ({
register: (data) => dispatch(register(data))
});
export default connect(null, mapDispatchToProps)(Form);
import React from 'react';
import { useForm } from 'react-hook-form';
import { connect } from 'react-redux';
const Form = ({ register, handleSubmit }) => {
const methods = useForm();
return (
<form onSubmit={handleSubmit(register)}>...</form>
);
};
export default connect(null, mapDispatchToProps)(Form);
``` |
70,886,556 | I have two dataframes in the following form:
df1
| id | name | df2\_id |
| --- | --- | --- |
| one | foo | template\_x |
| two | bar | template\_y |
| three | baz | template\_z |
df2
| id | name | value |
| --- | --- | --- |
| template\_x | aaa | zzz |
| template\_x | bbb | yyy |
| template\_y | ccc | xxx |
| template\_y | ddd | www |
| template\_z | eee | vvv |
| template\_z | fff | uuu |
For each value in `df1` where `df2_id` == `df2.id`, I'd like to iterate over `df2` and append the value of `df1.id` to `name` and `value` in each row to get:
df3
| id | concat\_name | concat\_val |
| --- | --- | --- |
| template\_x | aaa\_one | zzz\_one |
| template\_x | bbb\_one | yyy\_one |
| template\_y | ccc\_two | xxx\_two |
| template\_y | ddd\_two | www\_two |
| template\_z | eee\_three | vvv\_three |
| template\_z | fff\_three | uuu\_three |
Constraints/caveats:
* All relevant values are strings, no integers.
* Sometimes `df2.value` is empty, and I would like to keep it empty.
My approach was to use nested for loop with `df.iterrows`, but it's giving me trouble. | 2022/01/27 | [
"https://Stackoverflow.com/questions/70886556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15936178/"
] | The simplest way to do this is by raising the form state to the closest parent between the two components, then you can pass the change and submit handlers down to the requisite components.
See <https://reactjs.org/docs/lifting-state-up.html>
In the case of `react-hook-form` that means calling `useForm` in that highest shared component and passing down the functions, ideally using composition instead of prop drilling | ```
function handleForm(e) {
e.preventDefault()
// your code here
}
<button onClick={()=>{document.forms[0].submit()}} >Submit</button>
<form onSubmit={handleForm} >...</form>
```
For haters who dislike the answer:
```
const formRef=useRef();
function handleForm(e) {
e.preventDefault()
// your code here
}
<button onClick={()=>formRef.current.submit()} >Submit</button>
<form ref={formRef} onSubmit={handleForm} >...</form>
``` |
70,886,556 | I have two dataframes in the following form:
df1
| id | name | df2\_id |
| --- | --- | --- |
| one | foo | template\_x |
| two | bar | template\_y |
| three | baz | template\_z |
df2
| id | name | value |
| --- | --- | --- |
| template\_x | aaa | zzz |
| template\_x | bbb | yyy |
| template\_y | ccc | xxx |
| template\_y | ddd | www |
| template\_z | eee | vvv |
| template\_z | fff | uuu |
For each value in `df1` where `df2_id` == `df2.id`, I'd like to iterate over `df2` and append the value of `df1.id` to `name` and `value` in each row to get:
df3
| id | concat\_name | concat\_val |
| --- | --- | --- |
| template\_x | aaa\_one | zzz\_one |
| template\_x | bbb\_one | yyy\_one |
| template\_y | ccc\_two | xxx\_two |
| template\_y | ddd\_two | www\_two |
| template\_z | eee\_three | vvv\_three |
| template\_z | fff\_three | uuu\_three |
Constraints/caveats:
* All relevant values are strings, no integers.
* Sometimes `df2.value` is empty, and I would like to keep it empty.
My approach was to use nested for loop with `df.iterrows`, but it's giving me trouble. | 2022/01/27 | [
"https://Stackoverflow.com/questions/70886556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15936178/"
] | Just create a ref in the parent component, send it to the child component and assign that ref to an invisible submit button.
Finally, in the onClick event of the parent submit button simply call submitRef.current.click()
```
// ./From.js
import React from 'react';
import { useForm } from 'react-hook-form';
// This is the child component with a ref received from the parent
// and assigned to an invisible submit button
const Form = ({ submitRef }) => {
const {register, setValue, getValues, ...other } = useForm();
return (
<form onSubmit={handleSubmit(onSubmit)}>
...
<button ref={submitRef} type="submit" style={{ display: 'none' }} />
</form>
);
};
export default Form;
```
```
// ./Parent.js
import React, { useRef } from 'react';
import Form from './Form'
const Parent = () => {
const submitRef = useRef();
return (
<>
<button onClick={() => submitRef.current.click()}>Submit</button>
<Form submitRef={submitRef}/>
</>
);
};
export default Parent;
``` | ```
function handleForm(e) {
e.preventDefault()
// your code here
}
<button onClick={()=>{document.forms[0].submit()}} >Submit</button>
<form onSubmit={handleForm} >...</form>
```
For haters who dislike the answer:
```
const formRef=useRef();
function handleForm(e) {
e.preventDefault()
// your code here
}
<button onClick={()=>formRef.current.submit()} >Submit</button>
<form ref={formRef} onSubmit={handleForm} >...</form>
``` |
70,886,556 | I have two dataframes in the following form:
df1
| id | name | df2\_id |
| --- | --- | --- |
| one | foo | template\_x |
| two | bar | template\_y |
| three | baz | template\_z |
df2
| id | name | value |
| --- | --- | --- |
| template\_x | aaa | zzz |
| template\_x | bbb | yyy |
| template\_y | ccc | xxx |
| template\_y | ddd | www |
| template\_z | eee | vvv |
| template\_z | fff | uuu |
For each value in `df1` where `df2_id` == `df2.id`, I'd like to iterate over `df2` and append the value of `df1.id` to `name` and `value` in each row to get:
df3
| id | concat\_name | concat\_val |
| --- | --- | --- |
| template\_x | aaa\_one | zzz\_one |
| template\_x | bbb\_one | yyy\_one |
| template\_y | ccc\_two | xxx\_two |
| template\_y | ddd\_two | www\_two |
| template\_z | eee\_three | vvv\_three |
| template\_z | fff\_three | uuu\_three |
Constraints/caveats:
* All relevant values are strings, no integers.
* Sometimes `df2.value` is empty, and I would like to keep it empty.
My approach was to use nested for loop with `df.iterrows`, but it's giving me trouble. | 2022/01/27 | [
"https://Stackoverflow.com/questions/70886556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15936178/"
] | Just create a ref in the parent component, send it to the child component and assign that ref to an invisible submit button.
Finally, in the onClick event of the parent submit button simply call submitRef.current.click()
```
// ./From.js
import React from 'react';
import { useForm } from 'react-hook-form';
// This is the child component with a ref received from the parent
// and assigned to an invisible submit button
const Form = ({ submitRef }) => {
const {register, setValue, getValues, ...other } = useForm();
return (
<form onSubmit={handleSubmit(onSubmit)}>
...
<button ref={submitRef} type="submit" style={{ display: 'none' }} />
</form>
);
};
export default Form;
```
```
// ./Parent.js
import React, { useRef } from 'react';
import Form from './Form'
const Parent = () => {
const submitRef = useRef();
return (
<>
<button onClick={() => submitRef.current.click()}>Submit</button>
<Form submitRef={submitRef}/>
</>
);
};
export default Parent;
``` | The simplest way to do this is by raising the form state to the closest parent between the two components, then you can pass the change and submit handlers down to the requisite components.
See <https://reactjs.org/docs/lifting-state-up.html>
In the case of `react-hook-form` that means calling `useForm` in that highest shared component and passing down the functions, ideally using composition instead of prop drilling |
18,063,919 | Cheers Jasper Reports expert,
I'm a bit new with Jasper Reports so thanks for any help.
We are investigating the use of Jasper Reports Server as our main tool to offer our customers the reporting capabilities they need. We are a Java shop but would like our clients to mainly interface with JasperReports Server for reporting needs (as opposed to writing a custom app for this).
We have a requirement to display scientific data (signal trace data) that is contained in a BLOB field (it's some standard format but not well known). I've considered a couple of options:
1) Find some cool out of the box support for this (this seems unlikely)
2) Deploy a custom jar file and reference a method that produces a complete chart displayable via JR Server (It really seems like I should have come across a way to do this by now, but haven't seen it).
3) Deploy a custom jar file to jasper and reference a java method that makes the data understandable to JRServer and use the built in charting capability (We could write any java needed but I'm not sure how to integrate with JRServer).
4) Write a simple servlet to serve up the image we want in the chart (alas, something I understand how to do!).
Question: which of these are real options and have I considered the best options?
Thanks
Wayne. | 2013/08/05 | [
"https://Stackoverflow.com/questions/18063919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2653916/"
] | Is this what you're looking for?
```
$('.select').parents('.123');
```
Or maybe the more specific:
```
$('li.select').parents('ul.123');
``` | [jquery-class-selectors](http://api.jquery.com/class-selector/)
```
$('ul[class="123"] li.select');
//Or
$('li.select').parents('ul.123');
``` |
18,063,919 | Cheers Jasper Reports expert,
I'm a bit new with Jasper Reports so thanks for any help.
We are investigating the use of Jasper Reports Server as our main tool to offer our customers the reporting capabilities they need. We are a Java shop but would like our clients to mainly interface with JasperReports Server for reporting needs (as opposed to writing a custom app for this).
We have a requirement to display scientific data (signal trace data) that is contained in a BLOB field (it's some standard format but not well known). I've considered a couple of options:
1) Find some cool out of the box support for this (this seems unlikely)
2) Deploy a custom jar file and reference a method that produces a complete chart displayable via JR Server (It really seems like I should have come across a way to do this by now, but haven't seen it).
3) Deploy a custom jar file to jasper and reference a java method that makes the data understandable to JRServer and use the built in charting capability (We could write any java needed but I'm not sure how to integrate with JRServer).
4) Write a simple servlet to serve up the image we want in the chart (alas, something I understand how to do!).
Question: which of these are real options and have I considered the best options?
Thanks
Wayne. | 2013/08/05 | [
"https://Stackoverflow.com/questions/18063919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2653916/"
] | Is this what you're looking for?
```
$('.select').parents('.123');
```
Or maybe the more specific:
```
$('li.select').parents('ul.123');
``` | How about an alternative using the `has()` method:
```
$("ul.123").has("li.select")
```
---
<http://jsfiddle.net/6wB49/>
---
**[has()](http://api.jquery.com/has/)**
>
> **Description**: Reduce the set of matched elements to those that have a
> descendant that matches the selector or DOM element.
>
>
> |
18,063,919 | Cheers Jasper Reports expert,
I'm a bit new with Jasper Reports so thanks for any help.
We are investigating the use of Jasper Reports Server as our main tool to offer our customers the reporting capabilities they need. We are a Java shop but would like our clients to mainly interface with JasperReports Server for reporting needs (as opposed to writing a custom app for this).
We have a requirement to display scientific data (signal trace data) that is contained in a BLOB field (it's some standard format but not well known). I've considered a couple of options:
1) Find some cool out of the box support for this (this seems unlikely)
2) Deploy a custom jar file and reference a method that produces a complete chart displayable via JR Server (It really seems like I should have come across a way to do this by now, but haven't seen it).
3) Deploy a custom jar file to jasper and reference a java method that makes the data understandable to JRServer and use the built in charting capability (We could write any java needed but I'm not sure how to integrate with JRServer).
4) Write a simple servlet to serve up the image we want in the chart (alas, something I understand how to do!).
Question: which of these are real options and have I considered the best options?
Thanks
Wayne. | 2013/08/05 | [
"https://Stackoverflow.com/questions/18063919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2653916/"
] | Is this what you're looking for?
```
$('.select').parents('.123');
```
Or maybe the more specific:
```
$('li.select').parents('ul.123');
``` | **Hi,**
You can also try this....
```
<head runat="server">
<title></title>
<script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('ul').bind('click', function () {
$(this).parent().each(function () {
alert($(this).attr('title'));
});
});
$('li').bind('onclick', function () {
$(this).parent().each(function () {
alert($(this).html());
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div title="div">
<ul class="123" title="1111_1">
<li title="test_1">Test 1</li>
<li title="test_2">Test 2</li>
<ul class="qwe" title="qwe">
<li title="qwe_1">ABC 1</li>
<li title="qwe_2">ABC 2</li>
<ul class="123" title="123">
<li class="select" title="123_1">XYZ 1</li>
<li title="123_2">XYZ 2</li>
</ul>
</ul>
</ul>
</div>
</form>
</body>
</html>
```
**Thank you,
Vishal Patel** |
18,063,919 | Cheers Jasper Reports expert,
I'm a bit new with Jasper Reports so thanks for any help.
We are investigating the use of Jasper Reports Server as our main tool to offer our customers the reporting capabilities they need. We are a Java shop but would like our clients to mainly interface with JasperReports Server for reporting needs (as opposed to writing a custom app for this).
We have a requirement to display scientific data (signal trace data) that is contained in a BLOB field (it's some standard format but not well known). I've considered a couple of options:
1) Find some cool out of the box support for this (this seems unlikely)
2) Deploy a custom jar file and reference a method that produces a complete chart displayable via JR Server (It really seems like I should have come across a way to do this by now, but haven't seen it).
3) Deploy a custom jar file to jasper and reference a java method that makes the data understandable to JRServer and use the built in charting capability (We could write any java needed but I'm not sure how to integrate with JRServer).
4) Write a simple servlet to serve up the image we want in the chart (alas, something I understand how to do!).
Question: which of these are real options and have I considered the best options?
Thanks
Wayne. | 2013/08/05 | [
"https://Stackoverflow.com/questions/18063919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2653916/"
] | How about an alternative using the `has()` method:
```
$("ul.123").has("li.select")
```
---
<http://jsfiddle.net/6wB49/>
---
**[has()](http://api.jquery.com/has/)**
>
> **Description**: Reduce the set of matched elements to those that have a
> descendant that matches the selector or DOM element.
>
>
> | [jquery-class-selectors](http://api.jquery.com/class-selector/)
```
$('ul[class="123"] li.select');
//Or
$('li.select').parents('ul.123');
``` |
18,063,919 | Cheers Jasper Reports expert,
I'm a bit new with Jasper Reports so thanks for any help.
We are investigating the use of Jasper Reports Server as our main tool to offer our customers the reporting capabilities they need. We are a Java shop but would like our clients to mainly interface with JasperReports Server for reporting needs (as opposed to writing a custom app for this).
We have a requirement to display scientific data (signal trace data) that is contained in a BLOB field (it's some standard format but not well known). I've considered a couple of options:
1) Find some cool out of the box support for this (this seems unlikely)
2) Deploy a custom jar file and reference a method that produces a complete chart displayable via JR Server (It really seems like I should have come across a way to do this by now, but haven't seen it).
3) Deploy a custom jar file to jasper and reference a java method that makes the data understandable to JRServer and use the built in charting capability (We could write any java needed but I'm not sure how to integrate with JRServer).
4) Write a simple servlet to serve up the image we want in the chart (alas, something I understand how to do!).
Question: which of these are real options and have I considered the best options?
Thanks
Wayne. | 2013/08/05 | [
"https://Stackoverflow.com/questions/18063919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2653916/"
] | How about an alternative using the `has()` method:
```
$("ul.123").has("li.select")
```
---
<http://jsfiddle.net/6wB49/>
---
**[has()](http://api.jquery.com/has/)**
>
> **Description**: Reduce the set of matched elements to those that have a
> descendant that matches the selector or DOM element.
>
>
> | **Hi,**
You can also try this....
```
<head runat="server">
<title></title>
<script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('ul').bind('click', function () {
$(this).parent().each(function () {
alert($(this).attr('title'));
});
});
$('li').bind('onclick', function () {
$(this).parent().each(function () {
alert($(this).html());
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div title="div">
<ul class="123" title="1111_1">
<li title="test_1">Test 1</li>
<li title="test_2">Test 2</li>
<ul class="qwe" title="qwe">
<li title="qwe_1">ABC 1</li>
<li title="qwe_2">ABC 2</li>
<ul class="123" title="123">
<li class="select" title="123_1">XYZ 1</li>
<li title="123_2">XYZ 2</li>
</ul>
</ul>
</ul>
</div>
</form>
</body>
</html>
```
**Thank you,
Vishal Patel** |
9,607,537 | I'm using Visual Web Developer 2010 Express and SQL Server 2008 R2 Management Studio Express
Hey guys,
Pretty new at C# here. I'm trying to follow [this](http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson01) C# ADO.NET tutorial (currently on step [2](http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson02)), and I'm stumped. I'm following all the steps, and everything makes sense to me in it, but whenever I try to debug, it does not show anything (in the sense of the c# methods not printing out a table from Northwind database onto my webpage) in `WebApplication1`'s Default.aspx page.
For a while, I thought it was my connection string, `conn`, and I wasn't naming the `"Data Source"` attribute, which from my understanding is the name of the server I'm trying to connect to. It is all on a local machine, and I'm putting the correct server name.. I think. Server name is `AZUES-221\JDOESQLSERVER`
I'm properly escaping the backward slash, but I still don't know. Is there something in my coding that's flawed? Please help!
*C# code*
```
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Main(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn); //passed the connection
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{ Console.WriteLine(rdr[0]); }//selected in the table
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
```
*Thanks in advance* | 2012/03/07 | [
"https://Stackoverflow.com/questions/9607537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/994576/"
] | As your example seems to be a **WebProject** try to put your code within `Page_Load` eventHandler. Afterwards you should try to print your data to the `Debug` window or to a control within your webPage.
```
using System;
using System.Data;
// and all the others ...
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn);
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{
System.Diagnostics.Debug.WriteLine(rdr[0]); // or on the other hand
lblOutput.Text += rdr[0]; // as a "quick and dirty" solution!
}
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
```
You may it find very useful to have a look at [databound controls](http://www.asp.net/web-forms/tutorials/moving-to-aspnet-20/data-bound-controls) or just use another type of project (eg winForm, console, ...) | why would console.writeline show anything. you are not working on console.
in case just to see your output. use Response.writeline(rdr[0]); |
9,607,537 | I'm using Visual Web Developer 2010 Express and SQL Server 2008 R2 Management Studio Express
Hey guys,
Pretty new at C# here. I'm trying to follow [this](http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson01) C# ADO.NET tutorial (currently on step [2](http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson02)), and I'm stumped. I'm following all the steps, and everything makes sense to me in it, but whenever I try to debug, it does not show anything (in the sense of the c# methods not printing out a table from Northwind database onto my webpage) in `WebApplication1`'s Default.aspx page.
For a while, I thought it was my connection string, `conn`, and I wasn't naming the `"Data Source"` attribute, which from my understanding is the name of the server I'm trying to connect to. It is all on a local machine, and I'm putting the correct server name.. I think. Server name is `AZUES-221\JDOESQLSERVER`
I'm properly escaping the backward slash, but I still don't know. Is there something in my coding that's flawed? Please help!
*C# code*
```
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Main(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn); //passed the connection
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{ Console.WriteLine(rdr[0]); }//selected in the table
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
```
*Thanks in advance* | 2012/03/07 | [
"https://Stackoverflow.com/questions/9607537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/994576/"
] | As your example seems to be a **WebProject** try to put your code within `Page_Load` eventHandler. Afterwards you should try to print your data to the `Debug` window or to a control within your webPage.
```
using System;
using System.Data;
// and all the others ...
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn);
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{
System.Diagnostics.Debug.WriteLine(rdr[0]); // or on the other hand
lblOutput.Text += rdr[0]; // as a "quick and dirty" solution!
}
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
```
You may it find very useful to have a look at [databound controls](http://www.asp.net/web-forms/tutorials/moving-to-aspnet-20/data-bound-controls) or just use another type of project (eg winForm, console, ...) | Create a **Console application** instead of the Web Application you have created.
Otherwise you will run into similar issues considering you are new to C# (or Visual Studio in general) AND considering the rest of the tutorial uses Console.WriteLine heavily.
Then you can use the same code as shown in the tutorial.

Additonally if you are concerned about the slash in the database server (it is a database server instance), you may wanna try this:
```
SqlConnection conn = new SqlConnection(@"Server=AZUES-221\JDOESQLSERVER;Database=Northwind;Trusted_Connection=True;");
```
Source: [Connection Strings Reference](http://www.connectionstrings.com/sql-server-2005) |
9,607,537 | I'm using Visual Web Developer 2010 Express and SQL Server 2008 R2 Management Studio Express
Hey guys,
Pretty new at C# here. I'm trying to follow [this](http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson01) C# ADO.NET tutorial (currently on step [2](http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson02)), and I'm stumped. I'm following all the steps, and everything makes sense to me in it, but whenever I try to debug, it does not show anything (in the sense of the c# methods not printing out a table from Northwind database onto my webpage) in `WebApplication1`'s Default.aspx page.
For a while, I thought it was my connection string, `conn`, and I wasn't naming the `"Data Source"` attribute, which from my understanding is the name of the server I'm trying to connect to. It is all on a local machine, and I'm putting the correct server name.. I think. Server name is `AZUES-221\JDOESQLSERVER`
I'm properly escaping the backward slash, but I still don't know. Is there something in my coding that's flawed? Please help!
*C# code*
```
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Main(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn); //passed the connection
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{ Console.WriteLine(rdr[0]); }//selected in the table
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
```
*Thanks in advance* | 2012/03/07 | [
"https://Stackoverflow.com/questions/9607537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/994576/"
] | Create a **Console application** instead of the Web Application you have created.
Otherwise you will run into similar issues considering you are new to C# (or Visual Studio in general) AND considering the rest of the tutorial uses Console.WriteLine heavily.
Then you can use the same code as shown in the tutorial.

Additonally if you are concerned about the slash in the database server (it is a database server instance), you may wanna try this:
```
SqlConnection conn = new SqlConnection(@"Server=AZUES-221\JDOESQLSERVER;Database=Northwind;Trusted_Connection=True;");
```
Source: [Connection Strings Reference](http://www.connectionstrings.com/sql-server-2005) | why would console.writeline show anything. you are not working on console.
in case just to see your output. use Response.writeline(rdr[0]); |
26,734,569 | How do I add 2 background colours to a container div. I've seen some solutions that work but only with 50% height for each colour. I need one however to have a set height (see image).
My current solution is for background 1 to be an 1x260px background image with background 2 being a background colour. This however leaves you as you open the page with a flash of background colour 2 until background 1 is finished loading, I would like to avoid this flash. Here is the structure of the page:

Thanks for the help in advance!
**UPDATE:**
I couldn't get any of the solutions working properly in my context, but eventually solved it myself (I realise now my brief might've been slightly incomplete).
Here's my [JSFiddle](http://jsfiddle.net/zj8rrsow/2/)
Here's the Code:
```css
html, body {
margin:0;
padding:0;
}
.other-content {
background-color:lightblue;
width:100%;
height:20px;
}
.page-content {
width:100%;
background-color:lightgray;
}
.container {
width:600px;
height:700px; /* This height is flexible and can change to whatever value you want */
background-color:gray;
margin-top:-50px;
margin-left:auto;
margin-right:auto;
}
.white-bg {
background-color:dodgerblue;
height:50px;
width:100%;
}
```
```html
<div class="other-content"></div>
<div class="page-content">
<div class="white-bg"></div>
<div class="container"></div>
</div>
<div class="other-content"></div>
``` | 2014/11/04 | [
"https://Stackoverflow.com/questions/26734569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1500992/"
] | Try this
```
background: rgba(47,102,179,1);/* Old Browsers */
background: -moz-linear-gradient(top, rgba(47,102,179,1) 0%, rgba(255,255,255,1) 260px, rgba(255,255,255,1) 100%); /* FF3.6+ */
background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(47,102,179,1)), color-stop(260px, rgba(255,255,255,1)), color-stop(100%, rgba(255,255,255,1)));/* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, rgba(47,102,179,1) 0%, rgba(255,255,255,1) 260px, rgba(255,255,255,1) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, rgba(47,102,179,1) 0%, rgba(255,255,255,1) 260px, rgba(255,255,255,1) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, rgba(47,102,179,1) 0%, rgba(255,255,255,1) 260px, rgba(255,255,255,1) 100%); /* IE 10+ */
background: linear-gradient(to bottom, rgba(47,102,179,1) 0%, rgba(255,255,255,1) 260px, rgba(255,255,255,1) 100%);/* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#2f66b3', endColorstr='#ffffff', GradientType=0 );/* IE6-9 */
```
its gradient, if you don't like it, change 0% to 100% or play with parameters | **used to this**
css
```css
.nice{
width:500px;
height:500px;
margin:auto;
position:relative;
background:red;
color:white;
z-index:1;
}
.nice:after{
content:"";
position:absolute;
left:0;
right:0;
top:0;
bottom:70%;
background:green;
z-index:-1;
}
```
```html
<div class="nice">helo helo helo </div>
``` |
26,734,569 | How do I add 2 background colours to a container div. I've seen some solutions that work but only with 50% height for each colour. I need one however to have a set height (see image).
My current solution is for background 1 to be an 1x260px background image with background 2 being a background colour. This however leaves you as you open the page with a flash of background colour 2 until background 1 is finished loading, I would like to avoid this flash. Here is the structure of the page:

Thanks for the help in advance!
**UPDATE:**
I couldn't get any of the solutions working properly in my context, but eventually solved it myself (I realise now my brief might've been slightly incomplete).
Here's my [JSFiddle](http://jsfiddle.net/zj8rrsow/2/)
Here's the Code:
```css
html, body {
margin:0;
padding:0;
}
.other-content {
background-color:lightblue;
width:100%;
height:20px;
}
.page-content {
width:100%;
background-color:lightgray;
}
.container {
width:600px;
height:700px; /* This height is flexible and can change to whatever value you want */
background-color:gray;
margin-top:-50px;
margin-left:auto;
margin-right:auto;
}
.white-bg {
background-color:dodgerblue;
height:50px;
width:100%;
}
```
```html
<div class="other-content"></div>
<div class="page-content">
<div class="white-bg"></div>
<div class="container"></div>
</div>
<div class="other-content"></div>
``` | 2014/11/04 | [
"https://Stackoverflow.com/questions/26734569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1500992/"
] | Try this
```
background: rgba(47,102,179,1);/* Old Browsers */
background: -moz-linear-gradient(top, rgba(47,102,179,1) 0%, rgba(255,255,255,1) 260px, rgba(255,255,255,1) 100%); /* FF3.6+ */
background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(47,102,179,1)), color-stop(260px, rgba(255,255,255,1)), color-stop(100%, rgba(255,255,255,1)));/* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, rgba(47,102,179,1) 0%, rgba(255,255,255,1) 260px, rgba(255,255,255,1) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, rgba(47,102,179,1) 0%, rgba(255,255,255,1) 260px, rgba(255,255,255,1) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, rgba(47,102,179,1) 0%, rgba(255,255,255,1) 260px, rgba(255,255,255,1) 100%); /* IE 10+ */
background: linear-gradient(to bottom, rgba(47,102,179,1) 0%, rgba(255,255,255,1) 260px, rgba(255,255,255,1) 100%);/* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#2f66b3', endColorstr='#ffffff', GradientType=0 );/* IE6-9 */
```
its gradient, if you don't like it, change 0% to 100% or play with parameters | Here, I have done only using css and background color.
Working [JsFiddle](http://jsfiddle.net/LL9voo6m/)
HTML:
```
<div class="part-b">
<div class="background"></div>
<div class="container">
<div class="row">
Content
</div>
</div>
</div>
```
CSS:
```
.container {
width: 960px !important;
position: relative;
}
.part-b {
background: yellow;
overflow: hidden;
position: relative;
}
.part-b .background {
width: 100%;
height: 100px;
background-color: green;
}
.row {
height: 50px;
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.