qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
10,858,570 | Okay, I need a div to `fadeIn` on click, but only if a video is not playing, so I thought an if statement was the way to go. I want it so that the fade only happens if a video isn't playing. I'm not sure how to set it up. I tried
```
if($("#myVid") != "playing") {
$("#MyT").fadeIn(0);
}
```
I'm probably way off. Can I get some help please?
aaaand, I'm using html5. | 2012/06/01 | [
"https://Stackoverflow.com/questions/10858570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316405/"
] | Assuming you are using the HTML5 `<video>` tag, you can use the following code to determine if the video is currently playing:
```
var elem = $('#myVid')[0]; // get the DOM element
if(!elem.ended && !elem.paused) {
alert('playing');
}
```
See <https://developer.mozilla.org/en/DOM/HTMLMediaElement> for a description of the various properties. | try this:
```
var myvid = document.getElementById('myVid');
if (myvid.error) {
switch (myvid.error.code) {
case MEDIA_ERR_ABORTED:
alert("You stopped the video.");
break;
case MEDIA_ERR_NETWORK:
alert("Network error - please try again later.");
break;
case MEDIA_ERR_DECODE:
alert("Video is broken..");
break;
case MEDIA_ERR_SRC_NOT_SUPPORTED:
alert("Sorry, your browser can't play this video.");
break;
}
}
```
[source](http://www.chipwreck.de/blog/2010/03/01/html-5-video-dom-attributes-and-events/) |
2,829,046 | How to calculate this integral $$\int\_0^1 \frac{1-x}{(x^2-x+1)\log(x)}\;dx$$
In WolframAlpha, I found it equal to $$\log \left[ \frac{\sqrt{\pi}\;\Gamma\left(\frac23\right)}{\Gamma\left(\frac16\right)} \right]$$
I tried using the relation$\quad\int\_0^1 x^t\,dt = \frac{x-1}{\log x}\quad$ then dividing both sides by $\quad(x^2-x+1)\quad$ and calculating the double integral $\quad\int\_0^1 \int\_0^1 \frac{x^t}{x^2-x+1}\,dtdx\quad$ but I'm unable to calculate $$\int\_0^1 \frac{x^t}{x^2-x+1}\,dx$$
Any hints?
TIA | 2018/06/23 | [
"https://math.stackexchange.com/questions/2829046",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/488070/"
] | Multiply both the numerator and denominator by $1+x$ so the denominator now turns into the nicely looking $1+x^3$ factor instead of that hideous quadratic factor! Calling the integral $I$ gives$$I\stackrel{\text{def}}{=}\int\limits\_0^1dx\,\frac {1-x^2}{\log x(1+x^3)}$$
This resulting integral is actually very trivial when you know how to evaluate it. In fact, the natural logarithm in the denominator reminds us (hopefully) of a very similar integral which can be quickly evaluated using Feynman's Trick$$J(a)=\int\limits\_0^1dx\,\frac {x^a-1}{\log x}=\log(a+1)$$
Similarly, in this case, we make the exponent $a$ instead of two to consider the generalized case and differentiate with respect to the parameter. Calling the new integral $I(a)$, not to be confused with $I$, gives$$\begin{align\*}I'(a) & =\frac {\partial}{\partial a}\int\limits\_0^1dx\,\frac {1-x^a}{\log x(1+x^3)}\\ & =-\int\limits\_0^1dx\,\frac {x^a}{1+x^3}\end{align\*}$$
Using the infinite geometric series and integrating termwise, we get
$$I'(a)=\frac 16\psi\_0\left(\frac {a+1}6\right)-\frac 16\psi\_0\left(\frac {a+4}6\right)$$
Integrating to return back to our original integral $I(a)$, and recalling that $\psi(z)=\left[\log\Gamma(z)\right]'$, we get$$I(a)=\log\Gamma\left(\frac {a+1}6\right)-\log\Gamma\left(\frac {a+4}6\right)+\log\left[\frac {\Gamma\left(\frac 23\right)}{\Gamma\left(\frac 16\right)}\right]$$
The constant is readily found by substituting $a=0$ into $I(a)$ and observing that our integral evaluates to zero. Then it's just a matter of isolating $C$ and simplifying the result. When $a=2$, we get
$$\int\limits\_0^1 dx\,\frac {1-x^2}{\log x(x^2-x+1)}\color{blue}{=\log\frac {\sqrt{\pi}\log\left(\frac 23\right)}{\Gamma\left(\frac 16\right)}}$$
Which was to be shown. | Before you introduce the parameter, multiply the numerator and denominator by $1+x$. The integral you end up with can be expressed in terms of the Digamma Function. |
19,812 | I have to prove or disprove the implications in these two situations
1. $L^\* = \emptyset$ $\rightarrow$ $L$ is infinite
2. $L^+ = \emptyset$ $\rightarrow$ $L$ is infinite
Here are my thoughts.
1. I would say Kleene star operation (\*) is union of
$\qquad L^0 \cup L^1 \cup L^2 \cup \dots$
and since $\\_^0 = \{\epsilon\}$ (even $\emptyset^ 0 = \{\epsilon\}$), there is no language $L$ such that $L^\* = \emptyset$.
How to prove finiteness/infiniteness?
2. Only language $L$ where $L^+ = \emptyset$ is $\emptyset$ which is a finite language. But how to prove there is no other language that is inifinite and the argument is valid for it?
---
EDIT: will it help if I rewrite the implications $A \rightarrow B$ to $\neg B \rightarrow \neg A$ ?
1. $L$ is finite $\rightarrow$ $L^\* \neq \emptyset$
2. $L$ is finite $\rightarrow$ $L^+ \neq \emptyset$
2) can be now interpreted as $\emptyset^+ = \{\epsilon\}$ and $\emptyset$ is a finite language. So the implication doesn't work. | 2014/01/18 | [
"https://cs.stackexchange.com/questions/19812",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/12947/"
] | 1) You need to take a look at [this page](http://en.wikipedia.org/wiki/Vacuous_truth). Remember that there is an *implication* to be proved true or false.
2) Consider the fact $L \subseteq L^{+}$ and apply it to the case $L^{+} = \emptyset$. | You have to *prove or disprove*.
L\* *always* contains the empty string and is therefore not empty. "L\* is empty" is a false statement. Anything follows from a false statement. So yes, if L\* is empty (which it cannot be) then L is infinite. L is also finite. And empty. And anything else, and all at the same time.
Let L be a language containing at least one string s. Then L+ contains s and is not empty. But if L is empty then L+ is empty. Therefore is L+ is empty, L is empty. And "L+ is empty" is possible, therefore "L+ is empty" implies L is empty, and it implies that L is not non-empty and definitely not infinite. |
73,891,626 | I made a small container that runs a single shell script.
Its Dockerfile is as follows:
```
FROM centos:centos7.9.2009
RUN mkdir -p /var/lib/test
COPY ./ /var/lib/test/
RUN yum -y localinstall /var/lib/test/*.rpm
ENTRYPOINT ["sh /var/lib/test/test.sh"]
```
However, when I run the image, it returns the error:
```
#docker run -it test:1.0
/usr/bin/docker-current: Error response from daemon: oci runtime error: container_linux.go:290: starting container process caused "exec: \"sh /var/lib/test/test.sh\": stat sh /var/lib/test/test.sh: no such file or directory".
```
The script file definitely exists as I can replace its entrypoint with bash and manually execute it:
```
# docker run -it --entrypoint bash test:1.0
[root@e9361c3e67fa /]# sh /var/lib/test/test.sh
Shell script starts...
```
I read similar posts and confirmed that the permission of the script is correct, the return codes inside it were all `LF`.
And the shell script is really simple:
```bash
#!/bin/bash
echo "Test"
exit 0
```
What else can cause this problem? | 2022/09/29 | [
"https://Stackoverflow.com/questions/73891626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12129644/"
] | ***1st solution:*** Within single GNU `awk` you could try following code. Written and tested with shown samples only. Simple explanation would be, setting RS(record separator) as `\\${[^}]*}` and then in main program substituting values like `${` and `}` from RT and printing only required values as per requirement.
```
awk -v RS='\\${[^}]*}' 'RT{gsub(/^\${|}$/,"",RT);print RT}' Input_file
```
---
---
***2nd solution:*** With any `awk` please try following `awk` code.
```
awk '
{
while(match($0,/\${[^}]*}/)){
print substr($0,RSTART+2,RLENGTH-3)
$0=substr($0,RSTART+RLENGTH)
}
}
' Input_file
``` | >
>
> ```
> echo 'text${v1}text${v2}etc' |
>
> mawk 'gsub(OFS"+", __, $!(NF = NF)) + \
> gsub("^"(__) "|"(__)"$", _)^_ + gsub(__," /\f\b\b/ ")' \
> __='\300' \
> FS='(^[^$}{]*)?[$][{]|[}][^}{$]*|[\301]+' OFS='\301'
>
> ```
>
>
```
v1 /
/ v2
``` |
28,311,307 | I was trying to upload my project to GitHub on Android-Studio.
Pushing to GitHub master... process never ends and Version Control Console gives this Error:
```
GitHub --credentials get: github: command not found
'C:\Users\SA'EED~1\AppData\Local\Temp\git-askpass-2722525787662236837.bat" "Username'
is not recognized as an internal or external command, operable program or batch file.
```
I only find an empty repository on my GitHub. | 2015/02/04 | [
"https://Stackoverflow.com/questions/28311307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4526402/"
] | Evidently, `sleep_for` is not precise at all. The working solution for this issue is to enter a while loop until the desired duration is reached. This make the application "sleep" for precisely 2000 microseconds.
```
bool sleep = true;
while(sleep)
{
auto now = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(now - start);
if ( elapsed.count() > 2000 )
sleep = false;
}
``` | Quoted from cppreference (see [sleep\_for](http://en.cppreference.com/w/cpp/thread/sleep_for)):
>
> This function may block for longer than sleep\_duration due to scheduling or resource contention delays.
>
>
>
I think that is the most likely explanation. The details will depend on your environment, especially your OS.
In general, I see no portable way to avoid it (non-portable options include increasing thread priorities or reducing the nice level).
Another, however less likely, reason for time differences are external clock adjustments (e.g., caused by a ntp daemon). Using a [steady\_clock](http://en.cppreference.com/w/cpp/chrono/steady_clock) is a portable insurance against clock adjustments. |
110,623 | I have a table with a username as unique & primary key.
I ran this Query to order them in ascending order
```
ALTER TABLE `table` ORDER BY `Username` ;
```
So the rows are ordered like this
```
+-----------+----------+
| Username | Password |
+-----------+----------+
| soho16793 | test1 |
| soho4595 | test2 |
| soho504 | test3 |
| soho931 | test4 |
+-----------+----------+
```
But I want them like this
```
+-----------+----------+
| Username | Password |
+-----------+----------+
| soho504 | test3 |
| soho931 | test4 |
| soho4595 | test2 |
| soho16793 | test1 |
+-----------+----------+
```
How can I achieve this ? | 2015/08/11 | [
"https://dba.stackexchange.com/questions/110623",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/72527/"
] | I created a table called "billy".
```
mysql> SELECT * FROM billy ORDER BY f1;
+----------+-------+
| f1 | f2 |
+----------+-------+
| soho10 | test5 |
| soho12 | test1 |
| soho123 | test2 |
| soho1234 | test4 |
| soho222 | test3 |
+----------+-------+
5 rows in set (0.00 sec)
```
which doesn't give the correct sort order - 1234 is bigger than 222!
Then, from [here](https://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring), I got the SUBSTRING() function and formulated
the following SQL:
```
mysql> SELECT CAST(SUBSTRING(f1, 5, LENGTH(f1)) AS UNSIGNED)
AS fred, f2 FROM billy ORDER BY fred ASC;
```
which gives you the integers you require to sort on ("fred" is an alias for the new integer column):
```
+------+-------+
| fred | f2 |
+------+-------+
| 10 | test5 |
| 12 | test1 |
| 123 | test2 |
| 222 | test3 |
| 1234 | test4 |
+------+-------+
5 rows in set (0.00 sec)
mysql>
```
[This](https://stackoverflow.com/questions/12126991/cast-from-varchar-to-int-mysql) also helped for CASTing. And thanks to @oNare for his question in comments below which led me to change this post from using the [MID() function](https://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_mid) to the more standard SUBSTRING().
And the answer you require is given by
```
SELECT * FROM billy ORDER BY CAST(SUBSTRING(f1, 5, LENGTH(f1)) AS UNSIGNED) ASC;
+----------+-------+
| f1 | f2 |
+----------+-------+
| soho10 | test5 |
| soho12 | test1 |
| soho123 | test2 |
| soho222 | test3 |
| soho1234 | test4 |
+----------+-------+
5 rows in set (0.00 sec)
mysql>
``` | Following @oNare's throwing down of the SQL gauntlet, verily I resolved to take up the challenge to my SQL-hood and thus, in this the year of our Lord two thousand and fifteen, I thusly formulated the following palimpsest. I offered incantations to the SQL muses, received inspiration from the SQL daemons, had it carved into silicon and presented it to the SQL Supreme Being, aka the MySQL Query Optimiser! And lo and behold, the result of my travails.
I considered it to be of cardinal importance to both deal with the evil beast that is the NULL. Assuredly I speaketh unto thee and tell you that it is an abomination and an offece to the fundamental law of God and man for an entity to be equal and not equal to itself and anything else at the same time! It was also a requirement that an ORDER BY clause be imposed in accordance with the wishes of the Deities resident in the heavens!
The first laboured step of my Odyssey was to CREATE a TABLE
```
CREATE TABLE billy (f1 VARCHAR(10), f2 VARCHAR(10), first_dig INTEGER);
INSERT INTO billy VALUES ('on13', '12', 3);
INSERT INTO billy VALUES ('on24', '12', 3);
INSERT INTO billy VALUES ('onaree123', 'test3', 7);
INSERT INTO billy VALUES ('onaree22', '12', 7);
INSERT INTO billy VALUES ('soho10', 'test5', 5);
INSERT INTO billy VALUES ('soho12', 'test1', 5);
INSERT INTO billy VALUES ('soho123', 'test2', 5);
INSERT INTO billy VALUES ('soho1234', 'test4', 5);
INSERT INTO billy VALUES ('soho22223', 'test6', 5);
INSERT INTO billy VALUES ('to13', NULL, 3);
INSERT INTO billy VALUES ('to2', NULL, 3);
INSERT INTO billy VALUES ('to4', '12', 3);
INSERT INTO billy VALUES ('xxxx', 'yyyyy', 0);
INSERT INTO billy VALUES (NULL, 'zzsdfs', NULL);
INSERT INTO billy VALUES ('sfs5436', 'blah1', 4);
INSERT INTO billy VALUES ('onar87343', 'blah2', 5);
INSERT INTO billy VALUES ('sdsd0935' , 'blah3', 5);
INSERT INTO billy VALUES ('sss8765678', 'sfs', 4);
```
**Method 1** - read 'em and weep! A **1-liner** solution!!!
===========================================================
From [here](http://grokbase.com/t/mysql/mysql/054ph638hw/extract-numeric-value-from-a-string), I garnered this little beauty.
SELECT COALESCE(CAST(REVERSE(CONVERT(REVERSE(f1), UNSIGNED)) AS UNSIGNED), 0) AS My\_num from billy ORDER BY My\_Num;
If you don't mind NULLs, you can leave out the COALESCE.
(@oNare, I told you that I was "planning on my response blowing you away!" :-) )
Method 1.5 - ANOTHER **1-liner!!!** Can you **believe** it?
===========================================================
This is a bit of a "cheat"... :-)
I downloaded the source for MariaDB 10.0.21, compiled and installed it. Loaded my old pal "billy the table" with the script above and ran the following SQL.
SELECT f1, COALESCE(CAST(SUBSTRING(f1, REGEXP\_INSTR(f1, '[0-9]')) AS UNSIGNED), 0) AS fred FROM billy;
(for some reason '[:digit:]' fails - don't understand why. Anyone?)
Another reason not to use MySQL - no decent regex support - MySQL's implementation is a joke - and it's not as if it would take a lot of work to steal a BSD (or similar) licenced library!
Method 2
========
From this [post](https://stackoverflow.com/a/11134888/470530), I adapted the content and came up with this SQL. The reason that there's a subselect is that MySQL doesn't allow aliases in WHERE clauses. COALESCE can be used to make the query return 0 for NULL values of fred.
Strictly speaking, the IS NOT NULL is superfluous here, because fred <> 0 will eliminate NULLs also (0 is neither equal to, nor not equal to, NULL) - I put it in just to show that NULLs can be dealt with also.
```
SELECT t1.*
FROM
(
SELECT f1, fd,
(
CAST(SUBSTRING(f1,
LEAST
(
if (Locate('0', f1) > 0, Locate('0', f1), 999),
if (Locate('1', f1) > 0, Locate('1', f1), 999),
if (Locate('2', f1) > 0, Locate('2', f1), 999),
if (Locate('3', f1) > 0, Locate('3', f1), 999),
if (Locate('4', f1) > 0, Locate('4', f1), 999),
if (Locate('5', f1) > 0, Locate('5', f1), 999),
if (Locate('6', f1) > 0, Locate('6', f1), 999),
if (Locate('7', f1) > 0, Locate('7', f1), 999),
if (Locate('8', f1) > 0, Locate('8', f1), 999),
if (Locate('9', f1) > 0, Locate('9', f1), 999)
),
LENGTH(f1)) AS UNSIGNED)
) AS fred
FROM billy
) AS t1
WHERE fred <> 0 AND fred IS NOT NULL
ORDER BY fred;
```
Method 3 - World's **worst query ever** - AKA the brute force approach :-)
==========================================================================
I included this more as a joke than anything else.
I got this [here](https://stackoverflow.com/a/11134841/470530) - the original just had 10 REPLACEs - it was to eliminate digits, but I'm nothing if not flexible, so voilà:
```
SELECT t1.f1, t1.fd, t1.extracted
FROM
(
SELECT f1, fd,
CAST(
REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(f1, 'a', ''),
'b', ''),
'c', ''),
'd', ''),
'e', ''),
'f', ''),
'g', ''),
'h', ''),
'i', ''),
'j', ''),
'k', ''),
'l', ''),
'm', ''),
'n', ''),
'o', ''),
'p', ''),
'q', ''),
'r', ''),
's', ''),
't', ''),
'u', ''),
'v', ''),
'w', ''),
'x', ''),
'y', ''),
'z', '') AS UNSIGNED)
AS extracted
FROM
billy) as t1
WHERE extracted <> 0 AND extracted IS NOT NULL
ORDER BY extracted;
```
========================== FUNCTIONS ================
Sometimes a function just makes life easier - and although SQL is powerful, there are some situations where procedural logic breaks down (although, not here - I just wanted to learn something! :-)
Function 1.
===========
This [page](https://stackoverflow.com/a/11137329/470530) gives this function which returns the position of the first digit in a string. The interested reader is invited to use the function to obtain a *pos* for a SUBSTRING() function which extracts the integer component of the f1 field of billy.
```
DELIMITER $$
DROP FUNCTION IF EXISTS `find_first_int`$$
CREATE FUNCTION find_first_int(pData CHAR(10))
RETURNS INT
BEGIN
DECLARE vPos INT DEFAULT 1;
DECLARE vRes INT DEFAULT 0;
DECLARE vChar INT;
WHILE vPos <= LENGTH(pData) DO
SET vChar = ASCII(SUBSTR(pData, vPos, 1));
IF vChar BETWEEN 48 AND 57 THEN
RETURN IFNULL(vPos, 0);
END IF;
SET vPos = vPos + 1;
END WHILE;
RETURN 0; -- can choose RETURN NULL if desired.
END $$
DELIMITER ;
SELECT f1, find_first_int(f1) AS first_int FROM billy;
```
Function 2
==========
Got this baby [here](https://gist.github.com/slav123/4274088). I am puzzled though (anyone answering will get a +1). It's supposed to return a string (on the right hand side of the response - strings are right-justified). **But** I can add integers to it, therefore confused - really grateful for a resolution! Even the f1 value of 'xxxx' which gives a blank extnum can be added to.
And what **really** puzzled me (cost me > 1hr of cursing/swearing/pulling\_out\_of\_hair) is that this works for MySQL but fails for MariaDB.
```
DELIMITER $$
DROP FUNCTION IF EXISTS `extnum` $$
CREATE FUNCTION `extnum`(in_phone varchar(50)) RETURNS varchar(50) CHARSET latin1
NO SQL
BEGIN
DECLARE ctrNumber varchar(50);
DECLARE finNumber varchar(50) default ' ';
DECLARE sChar varchar(2);
DECLARE inti INTEGER default 1;
IF in_phone IS NULL THEN
RETURN '0';
END IF;
IF length(in_phone) > 0 THEN
WHILE(inti <= length(in_phone)) DO
SET sChar = SUBSTRING(in_phone, inti, 1);
SET ctrNumber= FIND_IN_SET(sChar,'0,1,2,3,4,5,6,7,8,9');
IF ctrNumber > 0 THEN
SET finNumber=CONCAT(finNumber,sChar);
ELSE
SET finNumber=CONCAT(finNumber,'');
END IF;
SET inti=inti+1;
END WHILE;
RETURN TRIM(finNumber);
ELSE
RETURN 0;
END IF;
END$$
DELIMITER ;
select f1, extnum(f1), extnum(f1) + 5 AS test, cast(extnum(f1) as unsigned) as My_Num, length(extnum(f1)) from billy;
``` |
21,707,347 | I have some mobile numbers stored in a Oracle DB. I have a stored procedure that carries out some checks around a variety of validations. The stored procedure is launched by a front end Windows application. One basic validation example is ensuring the mobile field is not null.
I'd like to add validation for: check the mobile number is at least 10 characters long, and do NOT count white spaces (leading, after or in the middle) If not, then ignore these mobile numbers.
Example: '188 123 4567'
'1881234567'
' 1881234 567 '
All thee above numbers should be taken as valid, where as:
'188 123 456'
'188123456'
' 1881234 567 '
Should fail. Can you assist with syntax? I'm still learning PL/SQL.
Here is an extract of the stored procedure I already have in place:
```
AND NOT EXISTS
( SELECT *
FROM person_a p
WHERE p.person_id = sa.person_id
AND p.mobile_ph_no = sa.mobile_ph_no
AND pu.a_mobile_ph_no IS NOT NULL
```
)
If the mobile number already stored on the DB is wrong, I just want to ignore it. Not correct it or modify it in any way. Simply if it doesn't meet the criteria, skip over it. | 2014/02/11 | [
"https://Stackoverflow.com/questions/21707347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/600423/"
] | You can use `replace` function. E.g.,
```
select replace('188 123 4567',' ','') from dual;
```
result:
```
1881234567
```
Oracle Database SQL Reference for `replace` <http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions134.htm>
See also "Using Regular Expressions in Oracle Database" <http://docs.oracle.com/cd/B19306_01/appdev.102/b14251/adfns_regexp.htm>
Regexp-es are very useful for tasks like this one. E.g. `regexp_count('188 123 4567','[[:digit:]]')` returns the number of digits in `188 123 4567` ignoring all non-digit characters. | Very straight forward code to check the length removing all spaces could be:
`select length(replace('1881234 567',' ','')) from dual` |
39,704,525 | In a blank page on chrome console I type:
```
var o={};
o.toString() == false // false
o.toString() == true // false
```
I'm expecting o.toString to be evaluated as an empty string and so falsy...
What is happening? | 2016/09/26 | [
"https://Stackoverflow.com/questions/39704525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5381289/"
] | >
> I'm expecting o.toString to be evaluated as an empty string and so falsy...
>
>
>
That expectation is at odds with the [specified behavior of `Object.prototype.toString`](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-object.prototype.tostring) (which is what `({}).toString` is), which is to output `"[object Object]"` for plain objects.
So what you're doing is
```
"[object Object]" == true
```
(or `== false`). If we follow the (convoluted) rules of [the abstract equality comparison algorithm](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-abstract-equality-comparison), that ends up being
```
Number("[object Object]") === Number(true)
```
...which is
```
NaN === 1
```
...which is `false`, because `NaN` isn't equal to anything.
Similarly
```
"[object Object]" == false
```
...ends up being
```
NaN === 0
```
...which is also `false`, because (again) `NaN` isn't equal to anything.
In a comment you've asked:
>
> So why not truthy?
>
>
>
There's a big difference between coercing a value to boolean, like this:
```
if (o.toString()) {
```
...and *comparing* it to a boolean via `==`, like this:
```
if (o.toString() == true) {
```
They're just defined fundamentally differently, because `==` goes through a defined series of steps to try to make the values things it can compare, and it doesn't bias toward booleans when doing that (it biases toward numbers and strings). | It's because `o={}` and function `toString` return you `"[object Object]"`
If you need to get `true` / `false` if object is empty use something like:
**ES5**
```
var o1 = {};
if(Object.getOwnPropertyNames(o).length !== 0) console.log('true');
else console.log('false');
```
**JQUERY:**
Check this: <http://api.jquery.com/jQuery.isEmptyObject/>
```
if($.isEmptyObject(o)) console.log('true');
```
**Loadash**:
```
if(_.isEmpty(o)) console.log('true');
``` |
5,452,207 | What would be the best way to acces the google calendar on android right now?
I found the following ways:
[google-api-java-client](http://samples.google-api-java-client.googlecode.com/hg/calendar-v2-atom-android-sample/instructions.html?r=default) - It's only an alpha. Authenticating, getting calendar list works, but updating calendar crashes in sample. +no documentation and bad sample codes anyway.
[hackity hack reverse engeneering](http://www.developer.com/ws/article.php/3850276/Working-with-the-Android-Calendar.htm) - Sounds bad, also, (propably) not futureproof.
[Google data api](http://code.google.com/intl/hu-HU/apis/calendar/data/2.0/developers_guide_java.html) - As far as I know, it does not support/work on android.
Are there any alternatives that I have missed? Are there any working examples out there? | 2011/03/27 | [
"https://Stackoverflow.com/questions/5452207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373248/"
] | I recently used [SignPost](http://code.google.com/p/oauth-signpost/) for this. It handles OAuth, and you can use it to sign your HTTP requests to get or post data to your calendars. I had trouble getting Google's Java API to work with Android since I think it relies on Java APIs that are not necessarily present in Android.
To make your requests, you can refer to this page: <http://code.google.com/apis/calendar/data/2.0/developers_guide_protocol.html> | Have you looked at the [Data API Developer's Guide: Java](http://code.google.com/apis/calendar/data/2.0/developers_guide_java.html)? You can also work directly with [HTTP request/response](http://code.google.com/apis/calendar/data/2.0/developers_guide_protocol.html), if things you want/need aren't supported in the Java API.
I haven't personally used the Java API, but I have worked directly with HTTP, and found it to be pretty straightforward. |
69,425,787 | Why and how did the program give the output?
```
#include <stdio.h>
int sum(int a ,int b , int c ){
return a , b ,c;
}
int main() {
int a=10, b=100 , c=1000 ;
int x = sum(a , b ,c);
printf("%d %d %d" ,x);
return 0;
}
```
Output : 1000 1000 100 | 2021/10/03 | [
"https://Stackoverflow.com/questions/69425787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14105722/"
] | Short answer: no, you cannot return multiple values (at least, not as you did). Good news, you do have some ways to return multiple values from a function:
---
### Method 1: use a `struct`
```c
typedef struct result {
int a;
int b;
int c;
} result_t;
result_t foo(int a, int b, int c) {
return (result_t) { a + 1, b + 1, c + 1 };
}
int main(void) {
result_t res = foo(1, 2, 3);
printf("res.a is %d\n", res.a); // OUTPUT: res.a is 2
return 0;
}
```
---
### Method 2: use pointers as function arguments
```c
void some_calc(int input, int* output1, int* output2) {
*output1 = input * 2;
*output2 = input / 2;
}
int main(void) {
int res1, res2;
some_calc(50, &res1, &res2);
printf("50 * 2 = %d and 50 / 2 = %d\n", res1, res2);
return 0;
}
``` | One way to achieve with structs,
```
#include <stdio.h>
struct Values
{
int a;
int b;
int c;
} values;
struct Values sum(int a ,int b , int c ){
return (struct Values){ a, b, c};
}
int main() {
int a=10, b=100 , c=1000 ;
struct Values x = sum(a , b ,c);
printf("%d %d %d\n" ,x.a, x.b, x.c);
return 0;
}
``` |
34,569,271 | I have a Bootstrap Modal in ASP.Net with MVC 5 which I use to edit an entry on a FullCalendar javascript plugin.
\_Edit.cshtml:
```
@model Models.CalendarEntry
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Edit Calendar Entry</h4>
</div>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
<h4>@Model.Title</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.CalendarEntryId)
@Html.HiddenFor(model => model.PostId)
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EntryDateTime, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="input-group" id="datetimepicker">
@Html.EditorFor(model => model.EntryDateTime, new { htmlAttributes = new { @class = "form-control" } })
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
@Html.ValidationMessageFor(model => model.EntryDateTime, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Length, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Length, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Length, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EntryStatus, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EnumDropDownListFor(model => model.EntryStatus, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.EntryStatus, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" type="button">Cancel</button>
<input class="btn btn-primary" type="submit" value="Save" />
</div>
<script>
$(document).ready(function ()
{
$("#datetimepicker").datetimepicker();
});
</script>
}
```
For some reason two things are happening that I cannot figure out why.
Firstly, the `glyphicon-calendar` does not sit next to the input:
[](https://i.stack.imgur.com/TDSHs.png)
Secondly, when the Modal Form load, all the other fields except for the datetime field gets populated with data, until I click the calendar glyphicon, then the datetime field gets populated with the current date and time. The value from the model never gets displayed.
Web interfaces are not my forté and would appreciate any assistance. | 2016/01/02 | [
"https://Stackoverflow.com/questions/34569271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1160367/"
] | turns out, that I needed to set options for the datetimepicker, more specifically, a default value it would seem like:
```
<script>
$(document).ready(function ()
{
$("#datetimepicker").datetimepicker(
{
defaultDate: '@Model.EntryDateTime',
showTodayButton: true,
format: 'YYYY-MM-DD HH:mm',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15
});
});
</script>
``` | Another quick solution is to also format the date like this in your javascript:
```
defaultDate: '@Model.EntryDateTime.ToString("yyyy-MM-dd HH:mm")'
```
The solution of using the [DisplayFormat] as an attribute is just as valid if not a better solution. |
38,968,441 | I have one `ObservableCollection<M> fooBar {get;set;}`. The class `M.cs` looks like this:
```
public class M{
private int _ID;
public int ID {
get {return this._ID;}
set {this._ID = value;}
}
private string _number;
public int Number {
get {return this._number;}
set {this._number = value;}
}
private string _power;
public int Power {
get {return this._power;}
set {this._power = value;}
}
/*
...
*/
}
```
Now I want to hide only the duplicates of the propery `Power`. Inside my `.xaml` code I wrote this:
```
<UserControl.Resources>
<CollectionViewSource x:Key="myCollection" Source="{Binding Path=fooBar}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Power"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</UserControl.Resources>
```
I bind this collection to my `ComboBox`.
```
<ComboBox Name="cbValues"
ItemsSource="{Binding Source={StaticResource myCollection}}"
DisplayMemberPath="{Binding Power}"
SelectedValuePath="{Binding Power}"
/>
```
The `ComboBox` is filled with the correct values, but there a still duplicates. How can I hide them? | 2016/08/16 | [
"https://Stackoverflow.com/questions/38968441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5576680/"
] | You have to define your variable `gettopic` outside the `click` event
```
var gettopic;
$(".buttons").click(function(){
if (gettopic)
{
gettopic.abort();
}
gettopic=$.post("topic.php", {id: topicId}, function(result){
// codes for handling returned result
});
})
``` | ```
var xhr = [];
$('.methods a').click(function(){
var target = $(this).attr('href');
//if user clicks fb_method buttons
if($(this).hasClass('fb_method')){
//do ajax request (add the post handle to the xhr array)
xhr.push( $.post("/ajax/get_fb_albums.php", function(msg) {
$(target).html('').append(msg).fadeIn();
}) );
} else {
//abort ALL ajax request
for ( var x = 0; x < xhr.length; x++ )
{
xhr[x].abort();
}
$(target).fadeIn();
}
return false;
});
```
Using jquery you can use in this way:
```
var xhr = $.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
``` |
54,212,561 | Not a real question, rather a suggestion if anyone has faced the same needs.
Suppose to have a github repository with many contributors making PR. What are the best tools to automatic merge PR with the following condition:
* in there is no activity for a while (e.g. 10 days) close the PR without merging it IF the author has NOT commit rights on the repo and merge it IF the author has commit rights
I found several useful tool, like github APP:
* [bulldozer](https://github.com/palantir/bulldozer) that merges PR based on conditions (but not *time* intervals)
* [policy-bot](https://github.com/palantir/policy-bot) that tags the PR as approved/not approved depending on some conditions
* [mergify](https://mergify.io/) that auto merges PR depending on different conditions (again, no *time* intervals)
* writing a webhook?
In some ways I think that a synergy between APPs and other tools can solve the problem, but maybe there is a smoother way to do this.
Someone has some suggestions? | 2019/01/16 | [
"https://Stackoverflow.com/questions/54212561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2509085/"
] | >
> In some ways I think that a synergy between APPs and other tools can solve the problem
>
>
>
As other tools, don't forget [GitHub Actions](https://github.com/features/actions), like (for [those regarding PR](https://github.com/sdras/awesome-actions#pull-requests)):
* [`actions/stale`](https://github.com/actions/stale): Warns and then closes issues and PRs that have had no activity for a specified amount of time.
* [`jrylan/github-action-stuck-pr-notifier`](https://github.com/jrylan/github-action-stuck-pr-notifier): Automatically label and mention/notify a user about stuck pull requests.
By looking at their implementation, you can make your own which will close a PR matching your criteria. | Jenkins can be used for this exact thing and more, and it doesn't necessarily need to be a GitHub repository, any git repo works the same.
For example, in my company we use it to scan BitBucket PR comments and perform complex commands according to the comments, allowing for validations, automation testing and more before performing potentially dangerous actions.
Jenkins can be easily integrated with your git repo, or also with GitHub.
<https://plugins.jenkins.io/github/>
<https://plugins.jenkins.io/git/> |
281,222 | I'm learning about oscillators, but I can't seem to get the tank to oscillate. I have built a very simple circuit using the 555 timer and a LC tank (sorry for the bad circuit layout, this was my first drawing):
[](https://i.stack.imgur.com/gYj7Z.png)
My voltage source is 5v, not 2v, I made a mistake in the drawing. According to the formula, I'm getting a 4 hertz signal at 66% duty cycle: 138ms - high, and 69ms low.
**I'm trying to produce the following pattern on my oscilloscope every time I get a signal from the 555:**. I do not have a specific goal for the frequency/voltage or any of the other factors, I just want to generate this pattern.
[](https://i.stack.imgur.com/cA6b8.jpg)
If I remove the inductor, the wave becomes as expected:
[](https://i.stack.imgur.com/gt5mt.jpg)
**But the problem is** - if I put back the inductor in the tank circuit, my binary signal becomes a flat line with randomized distortions, I can't even make out where the signal starts or ends, it looks very similar to this:
[](https://i.stack.imgur.com/AdOVi.jpg)
I thought maybe the inductor is too high of a value, so I tried to use 10uh inductor instead of 100uh, then I can see again my binary wave with slight distortions, but nothing close to oscillation.
I believe my values are totally off for the tank circuit or the frequency coming from the 555 is too high and the 100uh inductor can't work 'fast enought', but I know nothing about eletronics, so it's just a wild guess.
Any hints on where did I go off the track? | 2017/01/19 | [
"https://electronics.stackexchange.com/questions/281222",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/121002/"
] | You need a high impedance source to drive a parallel LC tank circuit with minimal damping. Think about what this tank circuit wants to do when it oscillates, it wants to slosh the energy between the capacitor and inductor and not interact with the "outside" world.
Thus ideally, when this resonates it will appear as a high value resistor. Now if you ring this tank circuit with a source such as the 555 which will have a relatively low output impedance, it is effectively going to dominate it and thus completely squash the natural behaviour of the tank circuit. Look up quality factor of resonators, and how to maximise it for a parallel tank circuit.
As an analogy imagine a child's swing, what your circuit is doing is giving that swing a push but at the same time holding it firmly thus not letting it oscillate!
The solution is simply to have a relatively large resistor perhaps something like 10K between the output pin and the tank circuit!
EDIT: Longer but informal explanation
As you seen unfamiliar with some terms, lets makes things less technical:
Lets get something straight. Lets assume for simplicity that your 555 output pin behaves like a perfect voltage source, i.e that no matter how much current you draw in/out it will always stay at the voltage it wants to stay at. You must follow this point carefully.
Now, if you follow, you must agree that the output pin will always stay at the voltage the 555 wants it to be at. Now consider the tank circuit which is ALSO connected to the output node, what does the tank circuit want to do to the output pin? It wants to creates a nice sine wave at the frequency of the tank circuit, ie RING.
So we just made two contradictory statements: The 555 perfect voltage source wants to keep the output pin stuck at whatever it feels like (firm grip on the swing analogy), but at the same time the tank circuit wants to make that very node oscillate at its own frequency. So who wins i ask? The answer in the ideal case is always going to be the voltage source by definition. So you will get not ringing by simply connecting the tank circuit to a perfect voltage source.
So, now the solution is to increase the output resistance (impedance) of the voltage source, ie we are trying to make it less ideal (so it loosens its grip on the swing after giving it the first push!) You can do that by adding some resistance between the tank and the voltage source.
This is a very informal explanation, hopefully this encourages you to read on and possibly dig into the math! | Ideally you need to feed the tank circuit from a current source and not a voltage source. The output from your 555 is a voltage source so try feeding the tank through a 1 kohm resistor (a compromise between a voltage and current source). You could even feed the tank via a small capacitor (such as 10 nF) to get voltage amplification but the Q of this circuit may be too high for what you want.
[](https://i.stack.imgur.com/TvESm.jpg)
The inverter on the left can be your 555 output.
You could also use a transistor to connect the tank to a (the) DC supply then quickly disconnect it using the transistor. The time period that the transistor is on should be equivalent to half the time period of the resonant frequency ideally. |
31,780,830 | In C, We can use char \* to point at a string. Just like
```
char *s = "Hello";
```
.
As it be seen, Neither the variable is located dynamically on heap because there is no any dynamical functions like malloc, nor it is defined to point a certain other variable.
So my question is, **Where is the literal string which variable [char \*s] points to stored logically?**
Is it stored in stack like any normal local variables? or, something like stack?
---
Actually, I am a graduate of Computer engineering department, but I haven't found and have been too much curious about how [char \* string] works logically. It is a really great honor to ask right this one now. | 2015/08/03 | [
"https://Stackoverflow.com/questions/31780830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4493512/"
] | The variable `char* s` is stored on the stack, assuming it's declared in a function body. If it is declared in a class, then it is stored wherever the object for the class is stored. If it is declared as a global, then it is stored in global memory.
In fact, any non-`static` and non-`thread_local` variable you declare in these three positions behave the same way, regardless of whether it is a primitive (i.e. `int`), an object (i.e. `vector<int>`), or a pointer (i.e. `const char*`).
If a variable is static, it is always stored in global space. If a variable is `thread_local`, each thread gets its own copy, and that copy will usually stored at the base of the stack for the corresponding thread.
The actual string `"Hello"`, which `s` points to, is stored in a constant global space somewhere, usually the `.data` segment. | String literals have *static storage duration*. That means they exist for the whole lifetime of your program. They may be stored in a non-writable area, and they may overlap with other string literals. Two different instances of the same literal may or may not coincide.
It is up to your implementation (compiler/linker/etc). to make a decision that complies with those requirements. |
13,670,298 | Currently everyone talks of two solutions:
1. jQuery UI plugin --> not feasible, because it uses too much space
2. jQuery Color (http://api.jquery.com/animate/) --> not feasible because I can't actually get a link to the plugin to download
So my question is, what is the smallest plugin I can use to allow this effect with jQuery v1.7.2? | 2012/12/02 | [
"https://Stackoverflow.com/questions/13670298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146366/"
] | You can get the [`jQuery Color`](https://github.com/jquery/jquery-color/) plugin from its GitHub repository.
```
span.value {
background-color: #0f0;
}
```
```
$("span.value").animate({
backgroundColor: "transparent"
}, 'slow');
```
[See a live example using jQuery Color.](http://jsfiddle.net/KVFZM/)
---
You can also make use of [CSS3 transitions](https://developer.mozilla.org/en-US/docs/CSS/Using_CSS_transitions).
```
span.value {
background-color: #0f0;
-o-transition-duration: 0.8s;
-moz-transition-duration: 0.8s;
-ms-transition-duration: 0.8s;
-webkit-transition-duration: 0.8s;
transition-duration: 0.8s;
}
.fade {
background-color: transparent;
}
```
```
$("span.value").toggleClass("fade");
```
[See a live example using CSS· transitions.](http://jsfiddle.net/KVFZM/) | you can do this by animate try
```
$('span').animate({'backgroundColor' : '#ffff99'});
```
or try
```
$("span").fadeOut("slow").css("background-color", "#ffff99");
``` |
477,229 | For some reason this problem which seemed fairly easy on the surface has given me a lot of trouble. I have a square who's side length changes based on an independent variable. The square's upper left corner is at the origin, and the square's lower right corner is at $(l\_f,-l\_f)$, where $l\_f$ is the length of the square.
Our rectangle must always have a width to heigth ratio of $1280/720$. When the square is at it's initial length, the length of the square and the height of the rectangle should be the same. Additionally, the square must always be directly in the middle of the rectangle (that is, the center of the square and the center of the rectangle coincide). And finally, the ratio of the square's length and the rectangles lengths must get linearly smaller as the square's length decreases, and linearly larger as the square's length increases. I need the equations for $(x\_i,y\_i)$ and $(x\_f,y\_f)$, where $x\_i$ and $y\_i$ are the coordinates of the top left corner of the rectangle, and $x\_f,y\_f$ are the coordinates of the bottom right corner of the rectangle, based on the following variables.
$d = $ an independent variable, in the domain $(0, \infty)$, initial value of $1$
$l\_i = $ constant (initial size of square...for my problem it is 250)
$l\_f = l\_i\cdot d \rightarrow$ (where $l\_f$ is the length of the square)
**My Attempt**
I believe my attempt at getting the y limits is correct.
$$y\_i = \frac{l\_f}{2} - \frac{l\_i}{2}$$ $$y\_f = \frac{l\_f}{2} + \frac{l\_i}{2}$$
The $x$ coordinates are the hard ones now. Because the initial height of the rectangle and the length of the square must be the same, we need a corrective term to add onto the $x$ coordinates. The following term worked (not sure if it's neccessary in the end though). $\frac{1}{2} \cdot l\_f(\frac{1280}{720} - 1)$. Then, if the independent variable changes from it's default value of 1, we need another term since the width and height of the rectangle can't continue to scale at the same rate, otherwise the 1280x720 ratio is not maintained. I thought this term would do the trick $\frac{1280}{720}(\frac{l\_f}{2} - \frac{l\_i}{2})$, but using these terms does not give me the correct answer. Using these terms, I get the following:
$$x\_i = \left(1 + \frac{1280}{720}\right) \left(\frac{l\_f}{2} - \frac{l\_i}{2}\right) - \frac{1}{2} \cdot l\_f\left(\frac{1280}{720} - 1\right)$$
$$x\_f = \left(\frac{l\_f}{2} + \frac{l\_i}{2}\right) - \frac{1}{2} \cdot l\_f\left(\frac{1280}{720} - 1\right) - \frac{1280}{720} \left(\frac{l\_f}{2} - \frac{l\_i}{2}\right)$$
Like I said this doesn't work though. Let me know if you have any tips, thanks! | 2013/08/27 | [
"https://math.stackexchange.com/questions/477229",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/87662/"
] | If I'm understanding everything correctly, here's what I think you're looking for:
\begin{align\*}
y\_i &= \dfrac{-l\_i}{2} - \dfrac{l\_f}{2} \\
y\_f &= \dfrac{-l\_i}{2} + \dfrac{l\_f}{2} \\
x\_i &= \dfrac{l\_i}{2} - \dfrac{\frac{1280}{720}l\_f}{2} \\
x\_f &= \dfrac{l\_i}{2} + \dfrac{\frac{1280}{720}l\_f}{2} \\
\end{align\*}
Here's what I did. Initially, the centre of the square/rectangle is at $(l\_i/2, -l\_i/2)$. Note that linearly scaling the square/rectangle by a factor of $d$ will not change this centre point. Now to get the corners, we simply have to either add or subtract half the dimensions of the rectangle. Initially, the rectangle has a height of $l\_i$, so scaling it by $d$ gives us a new height of $l\_f$. Since we know the aspect ratio, it follows that the new width must be $\frac{1280}{720}l\_f$. | From the answers you gave to my comments, I figured you mixed up the $y$-direction in your question. You say that the rectangle is centered at $(l\_f/2, -l\_f/2)$, but in your calculation you use $(l\_f/2, l\_f/2)$ to obtain the $y$-boundaries of your rectangle. (Note that you get $y\_f=l\_f$ for $d=1$ instead of $y\_f=-l\_f$ as you told me in a comment.)
Suppose the formulas for the $y$-boundaries are correct in your question and the center of the square is in fact at $(l\_f/2, l\_f/2)$ so everything fits together, I would guess you want the following $x$-boundaries for the rectangle:
$$\begin{align\*}
x\_i &= \frac{l\_f}2 - \frac{1280}{720} \cdot \frac{l\_i}{2} \\
x\_f &= \frac{l\_f}2 + \frac{1280}{720} \cdot \frac{l\_i}{2}
\end{align\*}$$ |
17,830,806 | I am using bottle for a POC restful service project. would someone kindly let me know what is the best way to decide if the caller wants me to send the response in JSON, XML, or HTML? I have seen some examples of this using request.mimetypes.best\_match, but that needs me to import flask. is there a way to do this in bottle itself?
Thanks a lot,
Reza | 2013/07/24 | [
"https://Stackoverflow.com/questions/17830806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/554421/"
] | You ajax request is asynchronous, so you must do it with callbacks, or (not recommended) add async: false:
```
$.ajax({
type: "get",
url: href,
async: false
```
One more detail, declare result variable in CheckAjax method and assign value to it when request completes and then return this variable. | on alerting only the 'returndata' you able to see "true" or "false"? ,try quoting them in your condition and give e.preventDefault a shot instead of return false |
25,692,262 | In my HTML, I have 2 lines that have the same class. I want to be able to target just the first element, but can't seem to figure it out. I am able to target both elements, but when I change the CSS to select the first child, it doesn't return anything.
Here is the CSS and the duplicate classes

If I use `svg g.highcharts-axis-labels`, it will select both elements.
I tried selecting the first child like below, but its not returning any elements with that CSS.
```
svg g.highcharts-axis-labels:nth-child(1)
```
Can someone point out the mistake I am making. | 2014/09/05 | [
"https://Stackoverflow.com/questions/25692262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3072086/"
] | So, for your question why "its not returning any elements with that CSS".
According to the definition
>
> The :nth-child(n) selector matches every element that is the nth
> child, **regardless of type**, of its parent.
>
>
>
With this selector and your html,
>
> svg g.highcharts-axis-labels:nth-child(1)
>
>
>
the parent is "svg", the child is to be a "g.highcharts-axis-labels" at position 1 (in the list of all children under "svg" tag).
But the child at position 1 is not a "g.highcharts-axis-labels". Therefore the result is "no element". | `.highcharts-axis-labels:nth-of-type(1)` should select the first element. |
53,636 | I am planning to visit Iran for 13 days and want to get a visa on arrival (I'm a national of an eligible country).
Does anyone have recent experience regarding VoA, and/or know the documentation required?
On the [website of Iran's foreign ministry](http://en.mfa.ir/) I cannot find anything (it says "under construction"), nor on the website of the consulate in my country. I am especially interested in the required documentation, as we are backpacking and won't be able to provide accommodation bookings for more than the first two nights.
Web search retrieves a lot of travel agencies that say that VoA is risky and advertise their services. They also varyiously state that invitation letters, hotel bookings or health insurance proofs are needed, but most seem outdated. Same holds for [Wikivoyage](https://en.wikivoyage.org/wiki/Iran#Get_in).
[Possibly related, but outdated and more general thread.](https://travel.stackexchange.com/questions/3507/how-to-get-a-visa-for-iran/44240#44240) | 2015/08/26 | [
"https://travel.stackexchange.com/questions/53636",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/33276/"
] | Oh, I did this last month!
A lot of websites and forums have mentioned problems in the past with others failing to get visa on arrival, and being rejected (even Aussies and Kiwis, which for me as a Kiwi is pretty unusual, most places think we're harmless).
However by the time I'd heard this, I was already on the road and had no Iranian embassy nearby to apply to, so I had to hope.
That day, on three separate flights, I know of about 8 people who had to get VoAs (we were all going to a wedding).
We needed:
* insurance. Travel insurance. The copy of my policy on my phone didn't count, you had to have a paper proof. If not, you are forced to buy insurance, at US$15. Not too bad, just annoying.
* paperwork. On arrival you'll apply at a window, and go pay for your visa on arrival.
* proof of address of where you're staying (initially, not every night). We had a hotel booked, and had their details on hand.
* money. The VoA costs cash - for us it was expensive, around US$140.
* proof of what you're doing in Iran. This is likely the hardest part. For us we had our friend's phone number, our hotel's phone number, and had them on standby to call. One group got thoroughly checked, with every number they had being called, while two of us on my flight just got stamped happily and told to enjoy. Your mileage may vary.
* we didn't have an invitation as such, as some others have claimed, but possibly if we weren't visiting a friend for his wedding, it may have been different.
* to be clear, we had accommodation for the first ... three nights, and nothing booked after that. We ended up travelling from Tehran to Shiraz, Yazd, Esfehan, Rasht and back, and just booked accommodation as we went. And trains/buses. None of that was required at the border. | [Timatic](https://www.timaticweb.com/cgi-bin/tim_website_client.cgi?FullText=1&COUNTRY=ir&SECTION=vi&SUBSECTION=is&user=KLMB2C&subuser=KLMB2C) used to state a passport photo and an authorisation code is required.
None of that applies anymore. All you need is an eligible passport and health insurance. Unless you can produce adequate evidence of already having health insurance covering Iran, you'll have to buy it on arrival for USD 18.
In practice, they will most likely also want an address where you're going, so do take note of the address of whatever accommodation you've booked. |
6,346,119 | How can I get the date of next Tuesday?
In PHP, it's as simple as `strtotime('next tuesday');`.
How can I achieve something similar in .NET | 2011/06/14 | [
"https://Stackoverflow.com/questions/6346119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/589909/"
] | ```
DateTime nextTuesday = DateTime.Today.AddDays(((int)DateTime.Today.DayOfWeek - (int)DayOfWeek.Tuesday) + 7);
``` | Now in oneliner flavor - in case you need to pass it as parameter into some mechanism.
```
DateTime.Now.AddDays(((int)yourDate.DayOfWeek - (int)DateTime.Now.DayOfWeek + 7) % 7).Day
```
In this specific case:
```
DateTime.Now.AddDays(((int)DayOfWeek.Tuesday - (int)DateTime.Now.DayOfWeek + 7) % 7).Day
``` |
13,061,251 | I am building a simple notes application and I want to add a static bar at the bottom of the TableView. For example, I want to add a help button. How can I do this to just my TableView?
So far:
I have added a toolbar through storyboard, but that makes it stick at the end of the last made tableView cell. I want it stuck to the bottom. I entered this code to do programmatically:
```
@property (strong, nonatomic) IBOutlet UIToolbar *toolbar;
```
in my tableViewController.h file and
```
[self.view addSubview:_toolbar];
[self.navigationController.view setFrame:self.view.frame];
```
in my tableViewController.m file in my `viewDidLoad` method
Thanks! | 2012/10/25 | [
"https://Stackoverflow.com/questions/13061251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use a standard UITableViewController with a storyboard. In "simulated metrics", go to the Bottom Bar menu and select "Toolbar". The toolbar appears. You can then add button items to it. | You can use the toolbar that is included in all UITableViews by default, and add UIBarButtonItems to it. Despite the name, UIBarButtonItems can be customized to be any kind of view. Then you add them to the property self.toolbarItems, which is available to UITableViews by default.
e.g.
```
UIBarButtonItem * textItem;
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 250, 48)];
label.text = @"ImportantText";
label.adjustsFontSizeToFitWidth = YES;
label.textAlignment = NSTextAlignmentRight;
textItem = [[ UIBarButtonItem alloc ] initWithCustomView:label];
UIBarButtonItem * switchItem;
UISwitch * switchCtrl = [[UISwitch alloc] init];
[switchCtrl addTarget:self action:@selector(toggleSomething:) forControlEvents:UIControlEventValueChanged];
switchItem = [[ UIBarButtonItem alloc ] initWithCustomView:switchCtrl];
self.toolbarItems = [ NSArray arrayWithObjects:
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
textItem,switchItem,nil ];
``` |
58,393,311 | inside the While-loop , why the first print statement ( which asks the user to enter a number ) is skipped in the first time? I think It's because I don't understand how hasNextInt() method works , I tried though and read about It but really didn't go far.
the easiest solution is to put one print statement outside the loop , I tried it and it worked, but I just wanna know why this statement is skipped in the first Iteration.
```
Scanner scanner = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int number;
while(scanner.hasNextInt()) {
System.out.print("Enter a number: ");
number = scanner.nextInt();
scanner.nextLine();
max = Math.max(max,number);
min = Math.min(min,number);
}
System.out.println("Max number is "+max);
System.out.println("Min number is "+min);
scanner.close();
``` | 2019/10/15 | [
"https://Stackoverflow.com/questions/58393311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10653593/"
] | You can comment out resources temporary in the module which you want to destroy, uncomment resources on recreation and you can follow the below steps to avoid the error.
Remove the provider from the module and Pass provider in the module explicitly,
```
module "pass_provider" {
source = "../module"
providers = {
aws = aws
}
}
```
Pass provider with alias,
```
module "pass_provider_alias" {
source = "../module"
providers = {
aws = "aws.alias_name"
}
}
``` | If you commented out/removed a module and you see this error then another option is `terraform state rm` to esentially forget about it. [Terraform state rm](https://www.terraform.io/docs/cli/commands/state/rm.html)
You definately want to destroy the resource, `terraform destroy -target=module.mymodule` but in some cases the resource isn't physical, for example a `random` within the module. Also if you are using Terraform Cloud and the workspace is VCS linked then you wont be able to run an `apply` or `destroy` locally. In these cases use `rm` and if there are lingering resources just delete them manually. |
4,778,365 | Coming from a C# background, I was more or less puzzled by the seemly weird behavior of returning method handling in C++. My concern now is for a method in C++, returning by reference is not a very useful technique, this is because-- unlike C#--any variable declared inside a method body will go out of scope once the the control exit the method.
So, in C++, [this](http://www.learncpp.com/cpp-tutorial/74a-returning-values-by-value-reference-and-address/) cannot even compile ( but an equivalent version in C# *can*):
```
int& DoubleValue(int nX)
{
int nValue = nX * 2;
return nValue; // return a reference to nValue here
} // nValue goes out of scope here
```
The only time where returning by reference is useful is when you are returning a reference to an existing data member in a class, or you are returning a reference to an element inside a parameter of the method. But in both cases there is really no need to return anything; as the returned reference is already freely available to the caller of the method.
So, my conclusion is, there is no need to use return by reference at all. Am I right? | 2011/01/24 | [
"https://Stackoverflow.com/questions/4778365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] | >
> The only time where returning by reference is useful is when you are returning a reference to an existing data member in a class, or you are returning a reference to an element inside a parameter of the method.
>
>
>
Loosely speaking, true. The variable might not be "owned" by the class (as in tied to its lifetime): it could have been specified to the class by some earlier function call, or a global/singleton known to the class but not part of it, or even a newly allocated area in shared memory or the heap (though returning a reference rather than a pointer suggests the ownership isn't being given to the caller), but ultimately the class must have some access to that data.
>
> But in both cases there is really no need to return anything; as the returned reference is already freely available to the caller of the method.
>
>
>
No, because objects can have private and protected members, and grant friendship to other classes or functions, so it's entirely possible that a called function can access (and hence return a reference to) some data that the caller has no direct access to.
Further, many functions find a specific variable to do some work on, then return a reference to it. If the caller needed to make a separate call to find that variable again, it could be inefficient (as well as verbose in the calling code).
>
> So, my conclusion is, there is no need to use return by reference at all. Am I right?
>
>
>
Nope... due to the flawed premise above.
Another non-necessary but convenient use of return by reference is illustated by typical streaming functions:
```
std::ostream& operator<<(std::ostream& os, const X& x)
{
return os << x.str();
}
```
Above, the reference to means say...
```
std::cout << x << y;
```
...is evaluated as...
```
(std::cout << x) << y;
operator<<(operator<<(std::cout, x), y)
```
Which all chains together nicely. Similarly:
```
while (std::cin >> x >> y)
...
```
...works not only due to the chaining for successive inputs to x and y, but also because std::cin is still available for evaluation in a boolean context, which ends up invoking another member function effectively asking whether the streaming operations worked. | It is correct that this doesn't work for returning a reference to something allocated on the stack. That simply can't work.
However returning by reference can still be extremely useful - for example, a collection's indexing operator can return a value by reference, thus enabling you to assign to that element in the collection. |
1,980,756 | I am looking to use/buy a OCR solution for my next iPhone app.
Searching through the answers on this site didn't really help me a lot.
Did anybody ever use ABBYY Mobile OCR Engine for iPhone?
What interests me is how good is it (recognition) and how much does it cost?
Thank you. | 2009/12/30 | [
"https://Stackoverflow.com/questions/1980756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32188/"
] | For anyone else who ends up at this thread looking for a general iPhone OCR solution (I realize this thread was originally ABBYY specific), there's a good Tesseract proof of concept app here: <http://github.com/rcarlsen/Pocket-OCR> | I had the same idea, and contacted them to ask for prices.
1000$ per year for the basic engine, another 1000$ if you want to use their business card module + up to 50% of each sale!!!
very cheap, isnt it? dont think about using the engine if you are not quite sure to sell at least 10.000 apps a year... |
315,188 | If a method takes an object of class A as parameter and analyzes its properties somehow, performs calculations etc. to verify this object, is it okay for class A to have a `boolean valid` field? After the method of class B completes verification of this object it sets the boolean flag accordingly.
The verification process needs some additional info based on objects of classes other than A, so it's impossible to put a verify method in A - the object can't just verify (or validate) itself, just like it doesn't make much sense for a `Car` class to have a repair method. But it make sense to have a `workingFine` flag I guess in a `Car`. Then is it better to store it as a flag in A? Or should I do something else? | 2016/04/08 | [
"https://softwareengineering.stackexchange.com/questions/315188",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/222736/"
] | In your case, the object itself is not "valid". It is "valid in some context". This context is defined as "additional info" you described. As such, it should be obvious in which context the object is valid.
I would say putting `IsValid` flag in the object doesn't make much sense in this case. Only case it would make sense if the `context` is closely tied to the object itself. In which case, the object itself can have reference to this `context`.
Otherwise, I would create special "validation" object, that would bind together the information about what object, what context and if it is valid. | Ideally, you shouldn't need to store this information explicitly at all. It should follow implicitly from the control flow of your program.
```
*;; Very easy to read*
**ROUTINE** ProcessItem(*item*)
**BEGIN**
**IF** IsValidItem(*item*) **THEN**
ProcessValidItem(*item*)
**ELSE**
ProcessInvalidItem(*item*)
**FI**
**END**
**ROUTINE** ProcessValidItem(*item*)
**BEGIN**
DoSomething(*item*)
DoAnotherThing(*item*)
DoThisThing(*item*)
**END**
**ROUTINE** ProcessInvalidItem(*item*)
**BEGIN**
DoSomethingElse(*item*)
DoAnotherThing(*item*)
**END**
```
Inside the subroutines `ProcessValidItem` and `ProcessInvalidItem`, I don't need a flag that tells me whether an item is valid. If the structure of your program implies the validity of an item, you also cannot forget checking it. Validity should be checked at exactly one point, if possible. Instead of combining the treatment of valid and invalid items in the same function and deciding repetitively what to do depending on a “valid” flag, separate the control flow into two distinct, straight-forward code paths and factor the parts that are common to the treatment of both, valid and invalid items, out into subroutines. I find the code shown above much cleaner than the following example.
```
*;; Not so easy to read*
**ROUTINE** ProcessItem(*item*)
**BEGIN**
*valid* ← IsValidItem(*item*)
**IF** *valid* **THEN**
DoSomething(*item*)
**ELSE**
DoSomethingElse(*item*)
**FI**
DoAnotherThing(*item*)
**IF** *valid* **THEN**
DoThisThing(*item*)
**FI**
**END**
```
If you do have to store the validity on a per-item base, this flag should be owned by whomever determines the validity.
If an object can validate itself, it should have a method that tells whether it is valid. Whether it validates itself each time this method is called or caches it in a *private* field is an implementation detail. It would clearly break encapsulation to let code outside that class mess with the value of that field.
On the other hand, if the object is validated by someone else, then this somebody is responsible for keeping the information – outside the object. Giving the object access to its externally determined validation status would be just as wrong as giving somebody else access to the object's internal state. A simple pair structure could be used to attach such information to an object – and remove it again when no longer needed. In an object-oriented setup, the flag could be replaced by polymorphism to save one word of storage for the cost of a virtual method call.
```
+-------------------------+
| *ValidatedItem<T>* |
+-------------------------+
| - item : T |
+-------------------------+
| + getItem() : T |
| + *isValid() : Boolean* |
+-------------------------+
^
|
+-------------------+-------------------+
| |
+-------------------------+ +-------------------------+
| ValidItem<T> | | InvalidItem<T> |
+-------------------------+ +-------------------------+
| + isValid() : Boolean | | + isValid() : Boolean |
+-------------------------+ +-------------------------+
``` |
2,554,934 | Is there a way to figure out where in an array a pointer is?
Lets say we have done this:
```
int nNums[10] = {'11','51','23', ... }; // Some random sequence
int* pInt = &nNums[4]; // Some index in the sequence.
...
pInt++; // Assuming we have lost track of the index by this stage.
...
```
Is there a way to determine what element index in the array `pInt` is 'pointing' to without walking the array again? | 2010/03/31 | [
"https://Stackoverflow.com/questions/2554934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] | Yes:
```
ptrdiff_t index = pInt - nNums;
```
When pointers to elements of an array are subtracted, it is the same as subtracting the subscripts.
The type `ptrdiff_t` is defined in `<stddef.h>` (in C++ it should be `std::ptrdiff_t` and `<cstddef>` should be used). | Yeah. You take the value of:
```
pInt - nNums
``` |
16,663,649 | I have a requirement where I need to check for multiple values in sqlite where clause. The query goes like this.
```
String sql = "SELECT * FROM _jobcard_table as t1 " +
" left join _customer_table as t2 on (t1._custid=t2._custid) " +
" left join _make_table as t3 on (t1._job_make=t3._makeid) " +
" left join _model_table as t4 on (t1._jobmodel=t4._modid) " +
" where _addedby='" + Globals.mid +
"' AND _jobestimatedate='"+curr+"' " +
" group by _jobregno order by _custname";
```
Here curr, is a arraylist of values, I need to check if the date is one of the values in the ArrayList, then return that row, how can I do that? I am able to check for one value say curr.get(0). But not sure how to check for multiple values, please help! | 2013/05/21 | [
"https://Stackoverflow.com/questions/16663649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2150969/"
] | First, You can not have translation `3x3` matrix for `3D` space. You have to use homogeneous `4x4` matrices.
After that create a separate matrix for each transformation (translation, rotation, scale) and multiply them to get the final transformation matrix (multiplying `4x4` matrix will give you `4x4` matrix) | Lets clear some points:
Your object consists of 3D points which are basically 3 by 1 matrices.
You need a 3 by 3 rotation matrix to rotate your object: R but if you also add translation terms, transformation matrix will be 4 by 4:
```
[R11, R12, R13 tx]
[R21, R22, R23 ty]
[R31, R32, R33 tz]
[0, 0, 0, 1]
```
For R terms you can have look at :<http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/>, they are dependent on the rotation angles of each axis.
In order to rotate your object, every 3D point is multiplied by this rotation matrix. For every 3 by 1 point you also need to add a 4th term(scale factor) which is 1 assuming fixed scale:
```
[x y z 1]'
```
Resulting product vector will be 4 by 1 and the last term is the scale term which is 1 again and can be removed.
Resulting rotated object points are these new 3D product points. |
51,461,156 | I have some script for workers and everytime I try to execute one specific worker, it executed all script workers I have instead.
this is how I run the script worker:
```
val stockTakingSync = PeriodicWorkRequest.Builder(
UploadStockTakingSyncWorker::class.java,
interval,
TimeUnit.MILLISECONDS)
.setConstraints(myConstraints)
val stockTakingSyncWork = stockTakingSync.build()
WorkManager.getInstance()?.enqueue(stockTakingSyncWork)
```
but this is return I got:
```
07-22 07:35:08.789 1327-1387/com.mockie.daikokuten D/:dump doSync: PrdPriceSyncWorker called
07-22 07:35:08.796 1327-1386/com.mockie.daikokuten D/:dump doSync: PrdSizeWorker called
07-22 07:35:08.803 1327-1388/com.mockie.daikokuten D/:dump doSync: PrdTypeSyncWorker called
07-22 07:35:10.120 1327-1404/com.mockie.daikokuten D/:dump doSync: PrdTypeSyncWorker called
07-22 07:35:10.123 1327-1386/com.mockie.daikokuten D/:dump doSync: PrdSizeWorker called
```
as you can see, all worker being executed it as well. | 2018/07/22 | [
"https://Stackoverflow.com/questions/51461156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4190539/"
] | I have been looking at different SO questions to solve this issue and none of them helped. My problem was using BrowserRouter in multiple different components. Same as [here](https://github.com/ReactTraining/react-router/issues/4975#issuecomment-344449879). | For me, the issue was that my entire app was wrapped with a `<Router>`, because that was how the boilerplate code was set up. Then I was copying snips from BrowserRouter docs, and did not remove the `<BrowserRouter>` wrapper around the code. Nested routers won't work properly. |
27,189,024 | I have these codes in my project:
```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
int intPos = getArguments().getInt(ARG_SECTION_NUMBER);
View rootView;
rootView = inflater.inflate(R.layout.fragment_main, container,false);
TableLayout ll = (TableLayout) rootView.findViewById(R.id.tableLayoutList);
View mTableRow = null;
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Far_DastNevis.otf");
for (int i =1; i <= 2000; ++i)
{
mTableRow = (TableRow) View.inflate(getActivity(), R.layout.mrowrayout, null);
final TextView txtBody = (TextView)mTableRow.findViewById(R.id.txtItem);
txtBody.setText("Some Text" + i);
txtBody.setId(i);
txtBody.setTypeface(tf);
mTableRow.setTag(i);
ll.addView(mTableRow);
}
return rootView;
}
```
It needs some seconds (or minutes) to load and I wanna show process dialog or something like this to users until it load.
But I can't use process dialog in onCreateView.
Please help me guys. | 2014/11/28 | [
"https://Stackoverflow.com/questions/27189024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2740930/"
] | There are mainly two ways with that you can solve it.
1. **getActivity() method:-** Use getActivity() method where you use context or this keyword.
2. If `you can not access getActivity out of your onCreateView method`, then make your **View variable global and use its context,** eg, if your **`View itemView. itemView.getContext()`**
This is the exact what you want. | ```
ProgressDialog pDialog;
pDialog = new ProgressDialog((Main)context);
pDialog.setMessage("Loading");
pDialog.show();
``` |
27,955,230 | I am returning an array of objects to a page that renders a slideshow based on a photo album.
I fetch my pictures from the database.
Before I return this array as a result, I would like to tack on a "Thumbnail" url property. This property does not exist on the AlbumPicture, but I want it in the response.
This illustrates the idea:
```
List<AlbumPicture> pics = db.AlbumPictures.Where(p => p.AlbumID == album.ID).OrderBy(p => p.RankOrder).ToList();
foreach(AlbumPicture p in pics)
{
p.AddPropertyThatDoesntExist("Thumbnail", ThumbManager.GetThumb(p.ID));
}
return Json(pics, JsonRequestBehavior.AllowGet);
```
What is the most elegant way to add this JSON field to my result set?
This question is so basic that it is probably a duplicate. However, I googled for 10 minutes and could only find janky solutions that depend on 3rd party libraries. I'm interested in the current "best practice".
Possible duplicate of: [How to add dynamically more properties to Json response from the controller](https://stackoverflow.com/questions/20324992/how-to-add-dynamically-more-properties-to-json-response-from-the-controller). However, that answer will make the dynamically added fields uncles instead of siblings to my AlbumPicture properties in the resulting JSON. | 2015/01/15 | [
"https://Stackoverflow.com/questions/27955230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/409020/"
] | The answer conanak99 provided is in my opinion the correct way to do this. Extensions like these are usually hidden in your core utilities anyway, and thus the reusable nature of his answer. If you are sure you will only use it for this purpose, you can refactor it to
```
public static dynamic AppendProperty<T>(this object value, string propertyName, T newValue)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
expando.Add(property.Name, property.GetValue(value));
expando.Add(propertyName, newValue);
return expando as ExpandoObject;
}
```
which will in turn yield the following code to do what you want:
```
var pics = db.AlbumPictures.Where(p => p.AlbumID == album.ID)
.OrderBy(p => p.RankOrder)
.Select(p =>
{
return p.AppendProperty("Thumbnail", ThumbManager.GetThumb(p.ID));
})
.ToList();
```
**Update ------------------------------**
If you are using automapper, or are willing to install it, this is another workaround that can be used in order to achieve the same result.
First, you create an extension class of the Album, with the added property
```
class AlbumExt : Album
{
public string Thumbnail { get; set; }
}
```
Then you create a new instance of the extended class in the select statement, copy the property values using automapper(or manually, if you don't have too many) into the new class, and set the thumbnail property.
```
var pics = db.AlbumPictures.Where(p => p.AlbumID == album.ID)
.OrderBy(p => p.RankOrder)
.Select(p =>
{
AlbumExt tmp = new AlbumExt();
AutoMapper.Mapper.DynamicMap(p, tmp);
tmp.Thumbnail = "new prop value";
return tmp;
})
.ToList();
```
Automapper basically just copies property values from one class to another using default conventions which are can be overridden if needed. | Not directly an answer to your question, but it seems to me that you are using something like the Entity Framework to handle your database connection with a "database first" approach. Now you don't want to add the "Thumbnail" property in the database, but also don't want to alter the dynamically created models.
Now I think the best approach would be to add the property to the model and not just to the JSON. In my opionion it will make it much easier to use and will also enable to possibility to use the thumbnail directly in a view if you ever need it.
I would add a class to the database project called `ExtendedModels.cs` and add something like the following
```
/// <summary>
/// This class is used to extend the AlbumPicture object from the database
/// </summary>
/// <remarks>
/// 2015-01-20: Created
/// </remarks>
public partial class AlbumPicture
{
/// <summary>An URL to the thumbnail.</summary>
public string Thumbnail
{
get
{
//ImageName is the actual image from the AlbumPicture object in the database
if (string.IsNullOrEmpty(ImageName))
{
return null;
}
return string.Format("/Thumbnail/{0}", ImageName);
}
}
}
```
Obviously it will also be added to the JSON output.
**UPDATE**
If you use code first you can use the `NotMapped` Annotation to make sure a property is not created in the database. See [Ignoring a class property in Entity Framework](https://stackoverflow.com/a/10385738/434949) for more details about different versions. So In your case it would be something like the following. You can change the get/set to what ever you want.
```
public class AlbumPicture
{
public string ImageName { get; set; }
[NotMapped]
public string Thumbnail{ get; set; }
}
``` |
5,295,936 | I have some whitespace at the begining of a paragraph in a text field in MySQL.
Using `trim($var_text_field)` in PHP or `TRIM(text_field)` in MySQL statements does absolutely nothing. What could this whitespace be and how do I remove it by code?
If I go into the database and backspace it out, it saves properly. It's just not being removed via the trim() functions. | 2011/03/14 | [
"https://Stackoverflow.com/questions/5295936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36545/"
] | If the problem is with UTF-8 NBSP, another simple option is:
```
REPLACE(the_field, UNHEX('C2A0'), ' ')
``` | Try using the MySQL `ORD()` function on the `text_field` to check the character code of the left-most character. It can be a non-whitespace characters that *appears* like whitespace. |
67,869,209 | I'm learning Clojure. I found some exercises which require finding indexes for values in an array which are, for example, lower than next value. In Java I'd write
```java
for (int i = 1; ...)
if (a[i-1] < a[i]) {result.add(i-1)}
```
in Clojure I found keep-indexed useful:
```clj
(defn with-keep-indexed [v]
(keep-indexed #(if (> %2 (get v %1)) %1) (rest v)))
```
It seems to works ok, but
1. is there a better way to do so?
2. This approach should work well for "find all values" or "find first value" (wrapped in `first`). But what if I need "find last". Then I have to either `(with-keep-indexed (reverse v))` or `(last (with-keep-indexed v))`. Is there better way?
*Edit: Example: for [1 **1** 2 2 **1** 2]*
```
(with-keep-indexed [1 1 2 2 1 2])
;;=> (1 4)
``` | 2021/06/07 | [
"https://Stackoverflow.com/questions/67869209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13069466/"
] | The logic of forming pairs of numbers and comparing each number to the next number in the sequence can be factored out in a [transducer](https://clojure.org/reference/transducers) that *does not care* about whether you want your result in the form of a vector with all indices or just the last index. Forming pairs can be done using [partition](https://clojuredocs.org/clojure.core/partition) as already suggested in the other answers, but I did not find a transducer implementation of that function, which would greatly facilitate. Here is a workaround that uses a mapping transducer along with some mutable state.
```
(defn indexed-pairs []
(let [s (atom [-2 nil nil])]
(comp (map #(swap! s (fn [[i a b]] [(inc i) b %])))
(remove (comp neg? first)))))
(defn indices-of-pairs-such-that [f]
(comp (indexed-pairs)
(filter (fn [[i a b]] (f a b)))
(map first)))
```
In this code, the function `indices-of-pairs-such-that` will return a transducer that we can use in various ways, for instance with [into](https://clojuredocs.org/clojure.core/into) to produce a vector of indices:
```
(into [] (indices-of-pairs-such-that <) [1 1 2 2 1 2])
;; => [1 4]
```
Or, as was asked in the question, we can use [tranduce](https://clojuredocs.org/clojure.core/transduce) along with a reducing function that always picks the second argument if we only want the last index:
```
(transduce (indices-of-pairs-such-that <) (completing (fn [a b] b)) nil [1 1 2 2 1 2])
;; => 4
```
This is the power of transducers: they decouple sequence algorithms from the results of those algorithms. The function `indices-of-pairs-such-that` encodes the sequence algorithm but does not have to know whether we want all the indices or just the last index. | There are many ways to solve a problem. Here are two alternatives, including a unit test using [my favorite template project](https://github.com/io-tupelo/clj-template). The first one uses a loop over the first (N-1) indexes in an imperative style not so different than what you'd write in Java:
```
(ns tst.demo.core
(:use tupelo.core tupelo.test))
(defn step-up-index-loopy
[xs] ; a sequence of "x" values
(let-spy
[xs (vec xs) ; coerce to vector in case we get a list (faster)
accum (atom []) ; an accumulator
N (count xs)]
(dotimes [i (dec N)] ; loop starting at i=0
(let-spy [j (inc i)
ival (get xs i)
jval (get xs j)]
(when (< ival jval)
(swap! accum conj i))))
@accum))
```
When run, it produces this output:
```
calling step-up-index-loopy
xs => [1 1 2 2 1 2]
accum => #object[clojure.lang.Atom 0x4e4dcf7c {:status :ready, :val []}]
N => 6
j => 1
ival => 1
jval => 1
j => 2
ival => 1
jval => 2
j => 3
ival => 2
jval => 2
j => 4
ival => 2
jval => 1
j => 5
ival => 1
jval => 2
```
The second one uses a more "functional" style that avoids direct indexing. Sometimes this makes things simpler, but sometimes it can appear more complicated. You be the judge:
```
(defn step-up-index
[xs] ; a sequence of "x" values
(let-spy-pretty
[pairs (partition 2 1 xs)
pairs-indexed (indexed pairs) ; append index # [0 1 2 ...] to beginning of each pair
reducer-fn (fn [accum pair-indexed]
; destructure `pair-indexed`
(let-spy [[idx [ival jval]] pair-indexed]
(if (< ival jval)
(conj accum idx)
accum)))
result (reduce reducer-fn
[] ; initial state for `accum`
pairs-indexed)]
result))
```
The function `indexed` is from [the Tupelo Clojure library](https://cljdoc.org/d/tupelo/tupelo/21.06.06/api/tupelo.core#indexed).
When you run the code you'll see:
```
calling step-up-index
pairs =>
((1 1) (1 2) (2 2) (2 1) (1 2))
pairs-indexed =>
([0 (1 1)] [1 (1 2)] [2 (2 2)] [3 (2 1)] [4 (1 2)])
reducer-fn =>
#object[tst.demo.core$step_up_index$reducer_fn__21389 0x108aaf1f "tst.demo.core$step_up_index$reducer_fn__21389@108aaf1f"]
[idx [ival jval]] => [0 [1 1]]
[idx [ival jval]] => [1 [1 2]]
[idx [ival jval]] => [2 [2 2]]
[idx [ival jval]] => [3 [2 1]]
[idx [ival jval]] => [4 [1 2]]
result =>
[1 4]
```
Both of them work:
```
(dotest
(newline)
(println "calling step-up-index-loopy")
(is= [1 4]
(step-up-index-loopy [1 1 2 2 1 2]))
(newline)
(println "calling step-up-index")
(is= [1 4]
(step-up-index [1 1 2 2 1 2])))
```
With results:
```
-----------------------------------
Clojure 1.10.3 Java 15.0.2
-----------------------------------
Testing tst.demo.core
Ran 2 tests containing 2 assertions.
0 failures, 0 errors.
```
The form `let-spy` is from the Tupelo Clojure library, and makes writing & debugging things easier. See the docs for more info. When satisfied everything is working, replace with
`let-spy` => `let`
Also be sure to study the [list of documentation sources](https://github.com/io-tupelo/clj-template#documentation) included in the template project, especially the Clojure CheatSheet.
---
Another solution using `keep-indexed` is pretty short:
```clj
(defn step-up-index
[xs]
(let [pairs (partition 2 1 xs)
result (vec
(keep-indexed
(fn [idx pair]
(let [[ival jval] pair]
(when (< ival jval)
idx)))
pairs))]
result))
(dotest
(is= [1 4] (step-up-index [1 1 2 2 1 2])))
``` |
62,138,428 | I have two columns that are datetime64[ns] objects. I am trying to determine the number of months between them.
The columns are:
```
city_clean['last_trip_date']
city_clean['signup_date']
```
Format is YYYY-MM-DD
I tried
```
from dateutil.relativedelta import relativedelta
city_clean['months_active'] = relativedelta(city_clean['signup_date'], city_clean['last_trip_date'])
```
And get the following error:
```
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
```
Does anyone know what could cause this issue? I feel like this is the most accurate way to calculate the number of months. | 2020/06/01 | [
"https://Stackoverflow.com/questions/62138428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10308255/"
] | This is Pandas, right? Try it like this:
```
# calculate the difference between two dates
df['diff_months'] = df['End_date'] - df['Start_date']
# converts the difference in terms of Months (timedelta64(1,’M’)- capital M indicates Months)
df['diff_months']=df['diff_months']/np.timedelta64(1,'M')
```
Or, if you have proper datetimes objects,
```
def diff_month(d1, d2):
return (d1.year - d2.year) * 12 + d1.month - d2.month
``` | You need to extract the property you want from the `relativedelta`, in this case, `.months`:
```
from dateutil.relativedelta import relativedelta
rel = relativedelta(city_clean['signup_date'], city_clean['last_trip_date'])
city_clean['months_active'] = rel.years * 12 + rel.months
``` |
3,089,457 | How do I go from this:
```
"01","35004","AL","ACMAR",86.51557,33.584132,6055,0.001499
```
to this:
```
ACMAR, AL
``` | 2010/06/22 | [
"https://Stackoverflow.com/questions/3089457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372685/"
] | I'm not quite sure why you'd want to parse a CSV file with a `Regexp` instead of a CSV parser. It makes your life *so* much easier:
```
require 'csv'
CSV.open('/path/to/output.csv', 'wt') do |csv|
CSV.foreach('/path/to/output.csv') do |_, _, state, city|
csv << [state, city]
end
end
``` | If it is an array — `[…].grep(/^[A-Z]+$/)`, if string — `"…".scan(/[A-Z]+/)` |
13,066,756 | Suppose I have a calculator class that implements the Strategy Pattern using `std::function` objects as follows (see Scott Meyers, Effective C++: 55 Specific Ways to Improve Your Programs and Designs):
```
class Calculator
{
public:
...
std::vector<double> Calculate(double x, double y)
{
std::vector<double> res;
for(const Function& f : functions)
res.push_back(f(x,y));
return res;
}
private:
std::vector<Function> functions;
};
```
where
```
typedef std::function<double(double,double)> Function;
```
Here is the problem I am facing: suppose functions `f` and `g`, both of type `Function`, perform expensive and identical calculations internally to get the final result. In order to improve efficiency, one could wrap all the common data in a `struct`, compute it once and provide to them as an argument. However, this design has several flaws. For example, this would cause a change in the signature of `Function`, which can result in unnecessary arguments being passed to some function implementations. Moreover, these common and internal data are no longer hidden from other components in the code, which can harm code simplicity.
I would like to discuss the following optimization strategy: implement a class `CacheFG` that:
1. Define a `Update` method that calculates its internal data with a given pair of doubles `x` and `y`; and
2. Define a `Check` method to determine if its current internal data was calculated with a given pair of doubles `x` and `y`.
What one could do then is to make `f` and `g` to share a common instance of the class `CacheFG`, which could be done using the `std::shared_ptr` construct. So, below would be the creation of `f` and `g` functions using auxiliary functions `f_aux` and `g_aux`.
```
double f_aux(double x, double y, const std::shared_ptr<CacheFG>& cache)
{
if(not cache->Check(x,y))
cache->Update(x,y);
...
}
std::shared_ptr<CacheFG> cache;
Function f = std::bind(f_aux, _1, _2, cache);
Function g = std::bind(g_aux, _1, _2, cache);
```
My questions are: (1) is this a safe approach for optimization? (2) is there a better approach for solving this problem?
Edit: After a few answers, I found out that my intention here is to implement a *memoization technique* in C++. I remark that only the last calculated state is enough for my purposes.
---
Thanks to *DeadMG*, I will now write here just an improvement over his approach. His idea consists of using a memoization technique with [variadic templates](http://en.wikipedia.org/wiki/Variadic_template). I just offer a slight modification, where I use the construct `std::decay<Args>::type` to ensure the definition of a `tuple` with non-reference types only. Otherwise, functions with const-reference arguments would cause compilation errors.
```
template<typename Ret, typename... Args>
std::function<Ret(Args...)> MemoizeLast(std::function<Ret(Args...)> f)
{
std::tuple<typename std::decay<Args>::type...> cache;
Ret result = Ret();
return [=](Args... args) mutable -> Ret
{
if(std::tie(args...) == cache)
return Ret(result);
cache = std::make_tuple(args...);
return result = f(args...);
};
}
```
In order to prevent the move of `result`, a copy of it is returned (`return Ret(result)`) when the provided `args` is the one cached. | 2012/10/25 | [
"https://Stackoverflow.com/questions/13066756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/418875/"
] | Why create your own class? There's no need for you to fail to re-create the interface of `unordered_map`. This functionality can be added as a re-usable algorithm based on `std::function` and `std::unordered_map`. It's been a while since I worked with variadic templates, but I hope you get the idea.
```
template<typename Ret, typename... Args>
std::function<Ret(Args...)> memoize(std::function<Ret(Args...)> t) {
std::unordered_map<std::tuple<Args...>, Ret> cache;
return [=](Args... a) mutable -> Ret {
if (cache.find(std::make_tuple(a...)) != cache.end())
return cache[std::make_tuple(a...)];
else
return cache[std::make_tuple(a...)] = t(a...);
};
}
```
I don't recall, offhand, whether `std::hash` natively supports tuples. If not, you might need to add it, or use `std::map` which does natively support them.
Edit: Hmm, I didn't notice that you wanted to *share* the cache. Well, this shouldn't be too difficult a problem, just stick an `unordered_map` member in Calculator and pass it in by reference, but the semantics of doing so seem a bit... odd.
Edit again: Just the most recent value? Even simpler.
```
template<typename Ret, typename... Args>
std::function<Ret(Args...)> memoize_last(std::function<Ret(Args...)> t) {
std::tuple<Args...> cache;
Ret result;
return [=](Args... a) mutable -> Ret {
if (std::tie(a...) == cache)
return result;
cache = std::make_tuple(a...);
return result = t(a...);
};
}
```
If you want to share between several Functions, then the alteration is the same- just declare it in the class and pass in as reference. | Before optimizing - measure. Then if you really perform many calculations with same value - then create this cache object. I'd like to hide cache checking and updating in `CacheFG::get(x, y)` and use it like `const auto value = cache->get(x,y)`. |
19,677,052 | I know that I can just say:
```
radians = degrees * Math.PI/180
```
However I expect there to be a built in framework method, as it is such a common requirement, however I cannot find one. Am I not looking hard enough or is it missing from the .net framework.
*(Please don’t insult me by telling me how to write my own method.)* | 2013/10/30 | [
"https://Stackoverflow.com/questions/19677052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/57159/"
] | I believe there is no such method.
>
> The angle, a, must be in radians. Multiply by Math.PI/180 to convert
> degrees to radians.
>
>
>
Above quote taken from [Math.Sin](http://msdn.microsoft.com/en-us/library/system.math.sin.aspx) remarks section.
If there is one method in .Net framework, documentation would suggest us to use that rather than giving the formula to implement. | AFAIK there is no built in functionality in the Framework (did the same research myself some time ago). I'e gone with your solution. |
13,285,213 | I'm talking about ones encoded in the format in which the twitter API returns its dates, like...
`"Tue Jan 12 21:33:28 +0000 2010"`
The best thing I thought of was to try to slice it up with regexes to become something more like...
`20100112213328`,
but there's *got* to be a better way. | 2012/11/08 | [
"https://Stackoverflow.com/questions/13285213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597180/"
] | You can just make a new Date object using a string like `"Tue Jan 12 21:33:28 +0000 2010"`.
```
var dateString = "Tue Jan 12 21:33:28 +0000 2010";
var twitterDate = new Date(dateString);
```
Then, you can simply use < and > to make comparisons.
```
var now = new Date();
if (now < twitterDate) {
// the date is in the future
}
``` | As far as the ECMAScript specification 5.1 goes (see 15.9.1.15), the only supported string interchange format for date-times is `YYYY-MM-DDTHH:mm:ss.sssZ` (along with shorter forms).
Otherwise (15.9.4.2):
>
> If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
>
>
>
I would use the regular expression based solution which is short and guaranteed to work anywhere; relying on the user's browser and localization parameters seems a little eerie to me. |
33,679,670 | I'm using NetBeans, and I am factoring out common classes into a library. I want to refer to classes in the library. I can do this easily enough by telling NetBeans that one project is dependent on another, the latter being a Java Library project.
The library project is called "ReVueLib". I have a folder there called "Stream", and in there is a class "StreamClient". The following is an abridged version of what matters:
```
package Stream;
class StreamClient {
public void StreamClient() {}
};
```
I have another project called "ReVueServer", and the main looks like this:
```
package revueserver;
import Stream.StreamClient;
public class ReVueServer {
public static void main(String[] args) {
Class c = StreamClient.class;
System.out.println(c.getName());
}
};
```
Now if I run this, it works fine and prints out "Stream.StreamClient". But say I want to refer to this class *without* the import. The reason is that in another project, I want to subclass Network.StreamClient as a class called StreamClient. This will help me to avoid refactoring a TON of existing code. In other words, I'm taking advantage of the namespace separation to be able to subclass and reuse the old name.
Unfortunately, if I take out the import, "Stream.StreamClient" doesn't work, nor does "ReVueLib.Stream.StreamClient" or anything else I've tried.
What FQCN do I need to use in order to reference this library class without "import"ing it? | 2015/11/12 | [
"https://Stackoverflow.com/questions/33679670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/929668/"
] | The proper name of a class in a package includes full name of the package. The `import` statement lets you avoid writing the prefix, but that is a compile-time trick. That is why your program prints the fully qualified name `Stream.StreamClient`, even though your program referred to the class by its short name `StreamClient`.
You can always rewrite your program to use full names for all your classes:
```
Class c = Stream.StreamClient.class;
```
or even
```
java.lang.Class c = Stream.StreamClient.class;
``` | You cannot refer to a class API without importing it (by either import or explicity fully qualified reference). Ever. Thats set in stone.
I think your misconception is that you could just write "Stream.class" somewhere and depending on whats on the classpath it will work. Thats true only to a very limited extent. While you can replace the Stream.class with another class of the same *qualified* name and API (that is methods and referenced fields), classes are *always* referred by their qualified name (thats package + class name).
Your problem sounds more like you need dependency injection with a common API. That allows you to select different implementations *of the same API*.
This works generally by defining the API, either as an interface or as abstract class:
```
package my.common;
public interface MyAPI {
public void doSomething();
}
```
Your program code can *only* operate on the defined interface and you will need the interface on the class path to compile and run.
You can then define any number of implementations of the interface anywhere you want:
```
package my.green;
public GreenAPI implements MyAPI {
public void doSomething() {
System.out.println("You reached green API");
}
}
```
Finally, you program need to be injected with the information how to get to the implementation at runtime. In the simplest case this can be done by passing the class name as a parameter somewhere, there are also frameworks to do this:
```
package something;
import my.common.MyAPI;
public MyAPIUser {
public static void main(String[] args) {
try {
Class<?> apiImpl = Class.forName("my.green.GreenAPI");
MyAPI api = (MyAPI) apiImpl.newInstance();
api.doSomething();
} catch (Exception e) {
e.printStakcTrace();
}
}
}
```
Thats, how the JRE manages to supply a common API for all JDBC drivers by the way. |
120,242 | The launchpad search field suddenly no longer accepts text input for me.

Any idea how to get this to accept text again? Searching for an app was so very useful. | 2014/02/07 | [
"https://apple.stackexchange.com/questions/120242",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/6759/"
] | I had the same problem today. On the Apple forums, I found a tip to delete the contents of `~/Library/Application Support/Dock` and to restart the Dock using `killall Dock` afterwards. This causes Launchpad to rebuild its database and supposedly should reactivate the search field.
I tried this and it did not work for me initially.
Meanwhile, I applied another tip, namely to repair the disk permissions with the disk tool (and then forgot about the topic).
A couple of hours later (now) - when I was looking for alternative solutions on Ask Different - I was suddenly able to search again in Launchpad.
So I expect, that either one of the tips or both in combination did the trick. | In the Launchpad, press `Cmd` + `Shift` + `esc`. The pad will fade and zoom, and when you hit it again it works so you can type again. |
173,612 | Context
=======
I'm looking for a new job and I've recognized a pattern at some of my previous places that I'd like to correct. I usually don't gain enough trust to influence process in a positive and lasting way. I've found most companies are very focused on business priorities, and for good reason. Many of these issues are or could quickly become existential issues. It's also a complex system with people with various goals and constant change.
I've learned what I want. I want a good, hopefully interesting job, where the people are nice and reasonably competent, and I make a decent wage. Then I want to go home. I have hobbies/health/interests to maintain and explore, and demands on my time will only increase. I'm happy to work extra in case of emergency, but I see no reason to work like I'm in a startup when I'm not being compensated that way nor was that part of the original agreement.
Summary
=======
I'm looking for strategies to:
* Gain trust in a new environment so I can maintain quality and avoid unnecessary emergencies
* Set boundaries so I can only work extra when there are real emergencies, instead of each time there's something new to learn, some arbitrary deadline no one agreed upon, or something else we could've planned for
Trust
=====
How do you gain trust in a new environment? I've seen other developers do it by working extra hard for the first couple of months to deliver things faster or fix languishing issues other developers haven't had time allocated to fix. I'm generally against this approach but I've seen it used effectively (though usually as a springboard to new projects/promotions). It sets a bad precedent and makes it harder to set boundaries in the future. Otherwise I like it, and if it was temporary I'd be all for it.
The only other way I can think of is learning more about people (learn their names quickly, their interests, and listen to them). I personally prefer to interact with people through good and interesting work, but hobbies are cool too. This approach also seems very slow.
Looking for more ideas to gain trust with management (as well as co-workers, but I usually don't have issues there).
Boundaries
==========
Onto the second (related) question. How do you set (and when do you reinforce) boundaries at work? I've heard of a couple strategies that I'll list below... but the closest I've gotten is just pointing out issues in the process (this ticket doesn't have AC, if I need to track down AC that takes more time. I'm happy to do it, but it obviously takes extra time that hasn't been allocated). Doing this is not a recipe for setting boundaries, it's a recipe for isolation. You get labeled as a complainer, rather than someone who's trying to do 2w of work in 2w, or someone who's trying to increase the health of the systems within/on which you work. Second closest was burning out a little. I'm looking for new ideas.
Quick other strategies I've heard of and flaws I can see:
* List your tasks and ask your boss to prioritize them, pointing out that you don't have enough time
+ This seems a bit confrontational to me, like it would damage the long-term relationship if you don't do it carefully
* Simply saying no
+ Also seems confrontational/damaging
+ Very vague... when do you say no? to what? how?
+ This also requires Business-Analyst + PO type work: you need to evaluate/get high-level estimates for incoming work and always know your current capacity so you can successfully back up your "no", or tell when you'll be able start on the new work.
* Conditional "no"s (similar to the above bullet), where you say "I can do that, but I'd need X training *first*, or I'd need some current project delegated)
+ Similar issues to above-- you really need to be on top of personal planning, rather than relying on the people who usually do that (POs/PMs/etc). This is mostly fine (especially as you get to more senior levels), but as always, takes more time and reduces the amount you can do when you're not planning
I want to have a good professional relationship with the people that I work with, but not at the expense of my time outside work or my personal and professional goals. I need to be able to (at the bare minimum) keep work at work. Ideally I'd keep the software/processes I work on/in maintainable and even fun to work with!
Thanks so much for reading and I'm hopeful to lean on your wisdom to create a more sustainable work life for myself so I can grow, accomplish more, and have a happy work/home life. | 2021/06/13 | [
"https://workplace.stackexchange.com/questions/173612",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/126752/"
] | Okay, there's a lot to unpack in your question.
**First up, you're conflating two separate things here:**
>
> How do you gain trust in a new environment? I've seen other developers
> do it by working extra hard for the first couple of months to deliver
> things faster or fix languishing issues other developers haven't had
> time allocated to fix.
>
>
>
The developers are *not* earning trust because they're 'working extra hard'. They're earning trust because they're achieving results. This isn't a meaningless distinction. I've seen people go overboard and work 10 hour days and they aren't trusted any more than before - because the 10 hours didn't actually achieve solid results. And I've seen people put in *fewer* hour than their contracted time, but are still greatly trusted - because they're getting good results.
If you want to be trusted, focus on:
* Being transparent
* Not letting small problems turn into larger ones
* Not causing problems in the first place
**Second, this really highlights what might be causing the issue:**
>
> List your tasks and ask your boss to prioritize them, pointing out
> that you don't have enough time - This seems a bit confrontational to
> me, like it would damage the long-term relationship if you don't do it
> carefully
>
>
>
You're not supposed to have a 100% harmonious relationship with your boss. That might sound bad/wrong, but think of it this way:
* Your boss has a boss of their own; that higher level boss wants something to happen by such-and-such a date. It's important!
* Your boss has subordinates who feel that the date isn't realistic/ahievable/whatever.
This is a faultline, and a lot of corporate scheduling involves resolving this dissonance. Maybe the boss is right, and the issue is that lower priority stuff is causing the problem - and that by doing reprioritization and restructuring, the date can actually be hit. Or maybe the subordinates are right, and there isn't a good way of hitting the date. Figuring out the path forward involves pushback from both groups.
But that's where you're failing - and why you're getting hit by burnout. Because you're not doing your part in the picture!
If the boss says, "We need XYZ by the end of 2021" and you don't feel that's achievable, *you need to tell them that.* If they contest it, you need to lay out the reasons why you won't hit the deadline.
In other words, you're responsible for being the other part of that faultline. And if you decide not to? Then management pushes more and more aggressive schedules (why not? nobody is telling them that their schedule won't work!) and the people trying to achieve them are getting burnt out.
Sound familiar?
In short, what you wrote in your "This doesn't work" section is actually *exactly* what you should be doing:
>
> List your tasks and ask your boss to prioritize them
>
>
>
... and estimate how many hours you think the tasks will take. It actually *is* your boss' job to prioritize your work. It's your boss' job to determine which deadlines will get missed.
**EDIT BASED ON COMMENTS:**
OP, I see you're getting tied up in the mechanics - jira vs whatever.
This really doesn't have anything to do with whether you use Jira or notecards or animal entrails. The important part is being upfront, transparent, and *confrontational* about a schedule dissonance.
Let's take your "2 weeks plus maintenance" example. Here's how the conversation with the boss *should* go:
* "How many hours will the task take?"
* "About 80."
* "So you'll be done in two weeks."
* "No. Maintenance typically takes up about 15 hours per week, and I'm tasked with doing the urgent report for the finance group, which will take another 10. So a tentative date, assuming nothing else comes up, would be about 4 weeks."
* "Four weeks! It's only an 80 hour task."
* "... and I could get it done in two, but only if someone else handles maintenance and the finance report - and nothing new comes along."
... do you see what's happening? You're letting the boss know: hey, as-is, this task won't be done in 2 weeks like you want. If it absolutely needs to be done in 2 weeks, there is a path forward - but it all depends on whether maintenance and the finance report are okay getting bumped until after the task.
Aka: the boss assigns the priorities, but you're ultimately responsible for pushing back if there's an unrealistic date (which there would be, if you needed to do all three ASAP.) And if anything new comes up, it's once again up to the boss on what gets the priority: the 80 hour task or the new one. | I feel like you're relating two unrelated things. But they're each quite easily answered independently.
Trust
-----
You gain trust by being good at your job, delivering results on time and in budget, and by, when asked for your opinion on something, being right. This can be done quickly or slowly depending on your role and activity level (I guess?), but this is how it is done.
* You cannot gain trust by working hard
* You cannot gain trust (except in the most antifunctional organizations) by knowing peoples' names or sharing hobbies or anything else personal
You gain trust by being reliably effective and effectively reliable. End.
Boundaries
----------
You set and enforce clear boundaries by setting, and enforcing, clear boundaries. Most of what you've written under this heading in your Q just... doesn't deal squarely with realities of work as I've experienced it, so I can't reply directly. It sounds like you may have some bad habits that you'll need to let go of. For instance, 'pointing out issues in the process' is utterly irrelevant to setting boundaries for work-life balance.
Much about how this works when the rubber hits the road will be dependent upon the method used to assign/track work, the cadence of your connection with superiors regarding workload, and other specifics. But, broadly speaking, don't work outside work hours. Do as much good work as you can in the time you're being paid to work. Communicate openly with whomever you report to about priorities and workload.
In your communications on this subject, you should:
* Be honest
* Be proactive
* Have a productive focus
* If you have questions, ask them.
* If you have blockers, discuss them.
* If anything is unclear, clarify it.
You really don't have to make things complicated. |
152,837 | How can I write an insert statement which includes the & character? For example, if I wanted to insert "J&J Construction" into a column in the database.
I'm not sure if it makes a difference, but I'm using Oracle 9i. | 2008/09/30 | [
"https://Stackoverflow.com/questions/152837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/466/"
] | I keep on forgetting this and coming back to it again! I think the best answer is a combination of the responses provided so far.
Firstly, & is the variable prefix in sqlplus/sqldeveloper, hence the problem - when it appears, it is expected to be part of a variable name.
SET DEFINE OFF will stop sqlplus interpreting & this way.
But what if you need to use sqlplus variables *and* literal & characters?
* You need SET DEFINE ON to make variables work
* And SET ESCAPE ON to escape uses of &.
e.g.
```
set define on
set escape on
define myvar=/forth
select 'back\\ \& &myvar' as swing from dual;
```
Produces:
```
old 1: select 'back\\ \& &myvar' from dual
new 1: select 'back\ & /forth' from dual
SWING
--------------
back\ & /forth
```
If you want to use a different escape character:
```
set define on
set escape '#'
define myvar=/forth
select 'back\ #& &myvar' as swing from dual;
```
When you set a specific escape character, you may see 'SP2-0272: escape character cannot be alphanumeric or whitespace'. This probably means you already have the escape character defined, and things get horribly self-referential. The clean way of avoiding this problem is to set escape off first:
```
set escape off
set escape '#'
``` | ```
INSERT INTO TEST_TABLE VALUES('Jonhy''s Sport &'||' Fitness')
```
This query's output : **Jonhy's Sport & Fitness** |
8,257,599 | In Google Map API v3, as the title, I only saw 2 types of animation in google map api, but I saw in some places the map marker animate like grow big when mouse over it? How to implement this? | 2011/11/24 | [
"https://Stackoverflow.com/questions/8257599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437808/"
] | Use marker's mouseover event handler and `setIcon()` method. You can use [dynamic icons](http://code.google.com/apis/chart/infographics/docs/dynamic_icons.html) from google chart api for this purpose, and change the `chld` attribute to make the icon grow:

<http://chart.googleapis.com/chart?chst=d_map_spin&chld=0.5|0|FF8800|15|_|>

<http://chart.googleapis.com/chart?chst=d_map_spin&chld=0.6|0|FF8800|15|_|>

<http://chart.googleapis.com/chart?chst=d_map_spin&chld=0.7|0|FF8800|15|_|>
Don't forget to set proper anchor point! For example:
```
marker.setIcon(new google.maps.MarkerImage(
'http://chart.googleapis.com/chart?chst=d_map_spin&chld=0.65|0|FF8800|15|_|',
null,
null,
new google.maps.Point(11, 43) // this is the proper anchor point for scale 0.65
));
``` | You could use your own image as a marker, then make use of the `scaledSize` property for the marker image to make it bigger when the `mouseover` event fires.
I don't know of a way to do this without doing some more complicated stuff like this. |
37,701,159 | I am working on `Rails application` where I am trying to fetch date of particular week but week start from not 1 January of year but some fixed date.
Like, `my week start from 8 july 2016 (08-07-2016)` so now i want to fetch start date and end date of any week.
```
Means week 1 start date -> 08-07-2016 and end date -> 14-07-2016.
```
Now i want to fetch any week start date and end date but how? I already tried but got solution of year start date not like this.
Any one have idea?
Thanks in advance. | 2016/06/08 | [
"https://Stackoverflow.com/questions/37701159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1498579/"
] | There is no simple way to pick a "random" key from a map.
I assume that "random" here means to pick it uniformly at random among the keys of the map.
For that, you need to pick a random number in the range `0`..`map.length - 1`. Then you need to get the corresponding key. Since `Map.key` is an iterable, you can't assume that you can do constant-time lookup in it, but you can use `elementAt` to get a specific iterable item without creating a new list.
So, basically:
```dart
randomKey(Map map) =>
map.keys.elementAt(new Random().nextInt(map.length));
```
(like you do it, but without the `toList`).
If you need *more* than one key, you are probably *better* off converting the keys to a list once, and then do lookups in the list in constant time. Example:
```dart
Iterable randomKeys(Map map) sync* {
var keys = map.keys.toList();
var rnd = new Random();
while (keys.length > 0) {
var index = rnd.nextInt(keys.length);
var key = keys[index];
keys[index] = keys.last;
keys.length--;
yield key;
}
}
```
On top of getting better performance, taking a copy of the keys also avoids concurrent modification errors. | I guess this is not what you're looking for, but actually it's a line shorter ;-)
```
void main() {
var map = {'a' :1, 'b':2, 'c':3};
final _random = new Random();
var values = map.values.toList();
var element = values[_random.nextInt(values.length)];
print(element);
}
```
[**DartPad example**](https://dartpad.dartlang.org/7a0af129a33e89b0241a7fd6fc431fac) |
17,295,086 | I want to do join the current directory path and a relative directory path `goal_dir` somewhere up in the directory tree, so I get the absolute path to the `goal_dir`. This is my attempt:
```
import os
goal_dir = os.path.join(os.getcwd(), "../../my_dir")
```
Now, if the current directory is `C:/here/I/am/`, it joins them as `C:/here/I/am/../../my_dir`, but what I want is `C:/here/my_dir`. It seems that `os.path.join` is not that intelligent.
How can I do this? | 2013/06/25 | [
"https://Stackoverflow.com/questions/17295086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1422477/"
] | You can use [normpath](http://docs.python.org/2/library/os.path.html#os.path.normpath), [realpath](http://docs.python.org/2/library/os.path.html#os.path.realpath) or [abspath](http://docs.python.org/2/library/os.path.html#os.path.abspath):
```
import os
goal_dir = os.path.join(os.getcwd(), "../../my_dir")
print goal_dir # prints C:/here/I/am/../../my_dir
print os.path.normpath(goal_dir) # prints C:/here/my_dir
print os.path.realpath(goal_dir) # prints C:/here/my_dir
print os.path.abspath(goal_dir) # prints C:/here/my_dir
``` | consider to use `os.path.abspath` this will evaluate the absolute path
or One can use `os.path.normpath` this will return the normalized path (Normalize path, eliminating double slashes, etc.)
One should pick one of these functions depending on requirements
In the case of `abspath` In Your example, You don't need to use `os.path.join`
```
os.path.abspath("../../my_dir")
```
`os.path.normpath` should be used if you are interested in the relative path.
```
>>> os.path.normpath("../my_dir/../my_dir")
'../my_dir'
```
Other references for handling with file paths:
* [pathlib](https://docs.python.org/3/library/pathlib.html) - Object-oriented filesystem paths
* [os.path](https://docs.python.org/3/library/os.path.html?#module-os.path)— Common pathname manipulations |
39,150,816 | I want to create Extension methods for dynamic type, but for some or the other reason i get error while compiling the code. below is my code sample
The method which i am using is
```
public List<State> getStates()
{
return new List<State>(){
new State{StateID="1",StateName="Tamil Nadu"},
new State{StateID="2",StateName="Assam"},
new State{StateID="3",StateName="Andra"},
new State{StateID="4",StateName="bihar"},
new State{StateID="5",StateName="Bengal"},
};
}
```
and my extension method is
```
public static class helper
{
public static IEnumerable<SelectListItem> getIntoDropDownState(this List<dynamic> data,string textField,string valueField)
{
return data.Select(x => new SelectListItem
{
Text = x.textField,
Value = x.valueField
});
}
}
```
My compilation error which i get is
>
> Compiler Error Message: CS1928:
> 'System.Collections.Generic.List'
> does not contain a definition for 'getIntoDropDownState' and the best
> extension method overload
> 'LearnAuthentication.Controllers.helper.getIntoDropDownState(System.Collections.Generic.List,
> string, string)' has some invalid arguments
>
>
>
I want to use the Extension method like this, and I am facing error
```
@Html.DropDownListFor(x => x.StateID, new LearnAuthentication.Controllers.Address().getStates().getIntoDropDownState("StateName", "StateID"), "Select State", 0)
```
can anyone help | 2016/08/25 | [
"https://Stackoverflow.com/questions/39150816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2711059/"
] | Ideally data should be filtered before rendering however you can also create a [variable in liquid](https://shopify.github.io/liquid/tags/variable/) to hold the number of stuff rendered
```
{% assign rendered = 0 %}
{% for study in site.data.studies %}
{% if study.category contains "foo" %}
<div class="col-sm-3">
<h3>{{ study.title }}</h3>
<div class="list-of-attributes">
<h6>attributes: </h6>
{{ study.attributes }}
</div>
</div>
{% assign rendered = rendered | plus: 1 %}
{% if rendered == 4 %}
{% break %}
{% endif %}
{% endif %}
{% endfor %}
```
The ideal solution as I said would be to create your own filter which does all the work (filter by category and limit the number of results)
```
{% assign filtered = site.data.studies | my_custom_filter %}
{% for study in filtered %}
<div class="col-sm-3">
<h3>{{ study.title }}</h3>
<div class="list-of-attributes">
<h6>attributes: </h6>
{{ study.attributes }}
</div>
</div>
{% endfor %}
``` | Presuming that your `category` is a string, not an array, you can do :
```
{% assign selected = site.data.studies | where: 'category','foo' %}
{% for study in selected limit:4 %}
<div class="col-sm-3">
<h3>{{ study.title }}</h3>
<div class="list-of-attributes">
<h6>Attributes: </h6>
{{ study.attributes }}
</div>
</div>
{% endfor %}
```
And if your `category` is a string like `"foo, bar, baz"` or and array of strings you can use the jekyll 3.2 `where_exp` filter like this :
```
{% assign selected = site.data.studies | where_exp:"item", "item.category contains 'foo'" %}
``` |
11,768,153 | How to get html like this:
```
<div id="generalContainer">
<div id="subContainer">
<div id="content">
</div>
</div>
</div>
```
from original html like this:
```
<div id="generalContainer">
<div id="content">
</div>
</div>
```
Thanks | 2012/08/01 | [
"https://Stackoverflow.com/questions/11768153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144140/"
] | ```
$("#content").wrap('<div id="subContainer">');
``` | ```
<div id="generalContainer">
<div id="content">blabla</div>
</div>
<script>
var ct = $('#generalContainer').html();
$('#generalContainer').html('<div id="subContainer">'+ct+'</div>');
</script>
``` |
3,541,353 | Problem 14 on p. 92 in Kolmogorov and Fomin Introductory real analysis defines a completely regular space by
Def. A $T\_{1}$ space T is completely regular iff. given any closed set $F \subseteq T$ and any point $x\_{0} \in T \setminus F$ there exists continuous real function $f$ such that $0 \leq f(x) \leq 1$ and $f(x) = 0$ if $x = x\_{0}$ and $f(x) = 1$ if $x \in F$.
The problem asks to show that every normal space is completely regular. I managed to do this by Urysohn's Lemma.
To show that complete regularity is heredetary. I managed to do this by using the complete regularity of the ambient space and then applying the restriction to the subspace to the Urysohn function in the ambient space.
The part of the problem which I am stuck on is to give an example of a completely regular space which is not normal. | 2020/02/10 | [
"https://math.stackexchange.com/questions/3541353",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | Here is an example (simpler than the one I mentioned in the comments) of a space which is completely regular but not normal.
The Sorgenfrey line is the space $\Bbb R\_\ell=(\Bbb R,\tau)$ where a basis for $\tau$ is given by $\{[a,b)\mid a,b\in\Bbb R\}$, this is a completely regular space (actually it is completely normal as well).
The Sorgenfrey plane is the space $\Bbb R\_s=\Bbb R\_\ell\times\Bbb R\_\ell$ with the product topology, or in other words $\Bbb R^2$ where a basis of the topology is given by the half open squares. This space is still completely regular, as the product of two completely regular spaces is completely regular (easy exercise).
Note that the set $\Delta=\{(x,-x\}\mid x\in\Bbb R\}$ is an uncountable closed discrete subspace of $\Bbb R\_s$ (draw a picture to convince yourself of this fact) and that this space is separable, since $\Bbb Q^2$ is a dense subset (every open set contains a Euclidean open set, so every open set intersects $\Bbb Q^2$).
Now if $\Bbb R\_s$ were normal, then we could use Tietze's extension theorem to show that there are at least $2^{2^{\aleph\_0}}$ continuous functions $\Bbb R\_s\to\Bbb R$, since every function $\Delta\to\Bbb R$ is continuous and there are $2^{2^{\aleph\_0}}$ distinct such functions, all of which could be extended to a function $\Bbb R\_s\to\Bbb R$.
But $\Bbb R\_s$ is separable, so a continuous function is determined by its values on $\Bbb Q^2$ and there's only $2^{\aleph\_0}$ functions $\Bbb Q^2\to\Bbb R$, contradicting the previous paragraph. Note that this argument really shows that a separable space with an uncountable closed discrete subset cannot be normal (so you can also use it to show that the Moore plane, another example of a space which is completely regular but not normal, is in fact not normal).
Let me finish by mentioning two useful resources for this kind of questions: [$\pi$-base](https://topology.jdabbs.com/), an online database of topological spaces, searchable by properties, and the book "counterexamples in topology" by Steen and Seebach, where $\Bbb R\_\ell$ and $\Bbb R\_s$ are the spaces 51 and 84 respectively. | There are a few classical examples that are often used in text books:
1. The [Niemytszki plane](https://en.wikipedia.org/wiki/Moore_plane) (aka the Moore plane, in the US). Quite elementary. Preferred example of Engelking's book.
2. The [(deleted) Tychonoff plank](https://en.wikipedia.org/wiki/Tychonoff_plank) (but this requires a little knowledge about ordinals).
3. The [Sorgenfrey plane](https://en.wikipedia.org/wiki/Sorgenfrey_plane), also quite elementary, preferred by Munkres' text, although he doesn't call it that.
4. A variant of 2.: $(\alpha(N) \times \alpha(D))\setminus \{(\infty\_1,\infty\_2)\}$ where $\alpha(N)=N \cup \{\infty\_1\}$ is the one-point compactification of a countable and discrete set $N$ and $\alpha(D)=D \cup \{\infty\_2\}$ is the one-point compactification of a discrete set $D$ of size $\aleph\_1$ (or continuum, if you prefer).
5. The [rational sequence topology](https://en.wikipedia.org/wiki/Rational_sequence_topology) on $\Bbb R$.
6. Mrówka $\Psi$ space for a so-called mad family.
1,3,5 can use the Jones' lemma for the proof of being non-normal, which implies that a separable normal space cannot have a closed discrete subspace of size $|\Bbb R|$. 2,4 have more direct proofs of non-separated closed sets. 6. is not normal as it's pseudocompact but not countably compact.
Queries in [$\pi$-base](https://topology.jdabbs.com/spaces?q=Completely%20Regular%20%2B%20~%24T_4%24) will give even more examples, like $\Bbb Z^{\omega\_1}$ and $\omega\_1 \times [0,1]^{[0,1]}$ etc. |
18,428,004 | Is it possible with javascript/jQuery to create objects on page load (or (document).ready) and then later use them, for example on keyup on an input.
If so, how? | 2013/08/25 | [
"https://Stackoverflow.com/questions/18428004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/263091/"
] | If you put all code in `$(document).ready{all code here}` then your variables won't go out of scope.
```
$(document).ready(function(){
var someObject={};
$("selector").click(function(e){
console.log(someObject);
});
});
```
If you're using onclick in html then I'd advice you to change that and move all JS code to JS file or `<script>` block (not in your html).
Instead of putting many variables on global scope you can namespace it (if you can't put all code in $(document).ready).
```
var myApplication = myApplication || {};//if myApplication doesn't exist then create it
myApplication.someObject = {};
```
Then even if your JS is spread over several files you can still maintain one myApplication object.
As gp mentioned; you can use data to add data to html elements:
```
$("#somebutton").on("click",function(e){
$(this).data("someObject",{});// you can use e.target instead of this as well
});
``` | Below find a example usage.
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
TODO write content
<div id="MytextID">My text </div>
<input type="text" id="inputId" name="name">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var x = $('#MytextID');
$('#inputId').keyup(function(){
alert(x.text());
})
})
</script>
</body>
</html>
``` |
8,727,984 | My English issnt so good sorry for that.
i have a array:
```
Array ( [name] => Array
(
[0] => Sorry the name is missing!
[1] => Sorry the name is to short!
)
)
```
Now I want to test with in\_array for eg "name".
```
if (in_array("name", $false["name"])) {
echo "the array keys";
}
```
but it dsnt work. could annybody help me please? thanks a lot. | 2012/01/04 | [
"https://Stackoverflow.com/questions/8727984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/933153/"
] | Try array\_key\_exists(): [link](http://www.php.net/array_key_exists)
```
if(array_key_exists('name', $false['name'])) {
echo $false['name'][0]; // or [1] .. or whatever you want to echo
}
``` | `in_array()` does not work with multi-dimensional arrays, so it is not possible to use `in_array()` here. When you are searching "name" in `in_array()` it searches in the first array and finds a key of the array named "name".
Better to use [array\_key\_exists](http://php.net/manual/en/function.array-key-exists.php) function. An example is given below: (remember it is only a suggestion. code may vary)
```
if(array_key_exists('name', $false['name'])) {
echo $false['name'][0]; // or [1] .. or whatever you want to echo
}
//$false['name'] array contains your searched data in different keys; 0,1,2,....
```
You can use `foreach()` to loop the first array then search using `in_array()` but that will not be a good method because it will take more time to find.
Best of luck :) |
9,543 | One of the current members of our group joined a little later than everyone else. His character's history wasn't developed too well, so I am running a one-off session so that the group can play out his history and get a better sense of the big picture.
I solicited a brief history from the player, and a major part of his story is a trial in which he was falsely convicted. I would like to run the trial as part of my one-off session.
How can I do this in a way that allows the players to actively participate and try to win even though they *must* lose to fit the story? Or should I just narrate the trial and not have them participate at all?
Note: Only one of the players will know that the outcome of the trial is predetermined, if that makes any difference. | 2011/08/19 | [
"https://rpg.stackexchange.com/questions/9543",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/1069/"
] | Put the players into story telling mode. A situation with a fixed outcome is not fun to game, but it can be fun to story tell.
I had a similar situation two sessions ago. We're fast forwarding through the levels because the game is coming to a close soon. The players had about a thousand miles of travel ahead of them. I figured we could skip that and I'd explain some of the challenges they faced along the road that caused them to gain four levels.
Instead, the wizard reminded me that he had a sigil for a linked portal at their destination. No travel time, no levels. Instead of taking their levels away or coming up with a contrived reason to stop the wizard from being cool, I told them the following:
>
> Well, I didn't plan for that. I was expecting months of travel to justify the levels you gained. You can still teleport there, but you're responsible for explaining how you gained those levels.
>
>
>
They started by suggesting that their destination was under siege and they had to break free. We went around the table and each player suggested a level's worth of obstacles and then the other players explained how they beat those hazards. I complicated matters when they made it too easy. And I tried to steer them away from 'we fight off an ambush in the night' type obstacles.
Anyway, the whole thing went over pretty well. The limitation of 'you must end up at destination having experienced 4 levels worth of obstacles' was taken well because it was something they could tell a story around rather than a limitation on what dice they could roll. Unless your players are in it for bashing down doors and rolling dice, I don't see any reason why this couldn't work for your group too. | First. Make sure everyone in your group understands that this is a no win situation. I feel like if they know they cannot win from the outset they will not be too disappointed whenever what they try does not work, at least to the full extent they were hoping it would. This does not have to be stated out right, it can be more subtle, but I feel like at least a hint of this should be there.
Second. Design your situation so that success does have some kind of effect. Could a persuasive argument lessen the sentence? Could they convince the court that instead of a maximum security prison the convicted player should go to a prison where he can be more easily rescued? I would make it so that if your players rolled/RP'd well enough there was some sense of accomplishment even if the overall mission will inevitably be a failure.
Hopefully the understanding that this is a somewhat on rails plot and back story building should lead to fairly cooperative players.
Finally, have a backup plan. If all of this goes to hell leave yourself a way out. Maybe this is only the first time the PC gets wrongfully accused. If somehow the players manage to change the outcome of the trial then let them continue on but look for a new opportunity to wrongfully accuse/imprison the PC a second time or approximate it in some way that fits the backstory...It might feel a bit railroady, but if you've warned them ahead of time it should be OK. |
21,396,928 | Let's say that I have an image that can be a variable width (min:`100px`, max:`100%` [760px]). I also have a `<p>` element that is to be shown right below the image. I'd like the `<p>` to end up with the same width as the `<img>`, but I can't seem to find an answer.
Here is the code involved in such a scenario [jsfiddle](http://jsfiddle.net/a9rEh/):
**html**:
```
<div id='page'>
<figure>
<img src='http://www.myimage.com/img.jpg'/>
<p>Hi there. I am some text. I would like to start where the image starts :(</p>
</figure>
</div>
```
**css**:
```
#page {
width:760px; /* arbitrary */
}
figure img {
display: block;
border: 1px solid #333;
max-width: 100%;
min-width: 100px;
margin: 0 auto;
}
figure p {
/* ??? */
}
```
Any ideas? | 2014/01/28 | [
"https://Stackoverflow.com/questions/21396928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2694234/"
] | You can use `display: table` on the `figure` and set a small width on it. Because it's a table layout it'll then become as wide as the content, in this case the image.
```
figure {
display: table;
width: 1%;
}
```
**[Demo](http://jsfiddle.net/a9rEh/6/)** | It is inheriting from `#page` div. not from the image. Please see the same fiddle updated.
But, You can control individual elements. You have to specify how you wish it to look like. |
28,911,634 | I'm receiving the following warning from mongodb about THP
```
2015-03-06T21:01:15.526-0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2015-03-06T21:01:15.526-0800 I CONTROL [initandlisten] ** We suggest setting it to 'never'
```
But I did manage to turned THP off manually
```
frederick@UbuntuVirtual:~$ cat /sys/kernel/mm/transparent_hugepage/enabled
always madvise [never]
frederick@UbuntuVirtual:~$ cat /sys/kernel/mm/transparent_hugepage/defrag
always madvise [never]
```
I did the trick by adding `transparent_hugepage=never` to `GRUB_CMDLINE_LINUX_DEFAULT` in `/etc/default/grub` and adding
```
if test -f /sys/kernel/mm/transparent_hugepage/defrag; then
echo never > /sys/kernel/mm/transparent_hugepage/defrag
fi
```
to `/etc/rc.local`
How on earth can I avoid the warning? | 2015/03/07 | [
"https://Stackoverflow.com/questions/28911634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2487227/"
] | MongoDB have updated their recommendation to use an **init.d** script now:
<http://docs.mongodb.org/master/tutorial/transparent-huge-pages/> | Verified that the defrag is examined without regard to the enabled:
```
$ cat /sys/kernel/mm/transparent_hugepage/enabled
always madvise [never]
$ cat /sys/kernel/mm/transparent_hugepage/defrag
[always] madvise never
$ service mongod start
... (in log) WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'
$ echo 'never' > /sys/kernel/mm/transparent_hugepage/defrag
$ cat /sys/kernel/mm/transparent_hugepage/defrag
always madvise [never]
$ service mongod stop
$ service mongod start
... (no warning in log)
```
Therefore, the fix to this bug is to first look at transparent\_hugepage/enabled, and if it is never, don't bother looking at the irrelevant transparent\_hugepage/defrag setting.
[Source](https://jira.mongodb.org/browse/DOCS-5108). |
57,466 | I'm looking to replace my water heater. I currently have a 15 year old 40 gallon gas water heater, and it's time to go. I had several quotes from local plumbers, and choked at the prices. I'm going to go with a 50 gallon Rheem from Home Depot, and am going to do it myself, and I want to do it legally, to code, and inspected.
I have a good deal of experience with plumbing and electrical installation (copper pipe soldering, 110V and 220V electrical, etc), and want to do this the right way.
The heater sits in the basement on a concrete slab, in the utility room, which is near the floor drain. The current water heater does not have a pan, but I'm planning on installing one, and routing the output drain from the pan to the floor drain (with an air gap). I'm planning on doing the same with the relief valve off of the water heater, keeping the two drain lines separated, and running both to the floor drain (keeping that all important air gap between the end of the drain pipes and the floor drain opening).
Anyway, I've been looking through the county's website (I live in unincorporated Jefferson County, Colorado) and have requested an account to get a permit. The county directs me to the universal plumbing code. I was able to obtain a copy of it, and started reading through it, and it seems extremely vague. I'm not sure what codes I need to observe for installation of a replacement water heater.
One thing that I will be testing for is the in-flow water pressure for the house from the city. If that is too high (over 80 PSI), I'll need to install a pressure regulator, which, as I understand in my county is another permit. If I need to put the pressure regulator in, I'll need to also add an expansion chamber to the cold-water side of the water heater, as the additional pressure from heat expansion can no longer be relieved to the city, as it's now a closed system.
The cold water inlet to the existing water heater already has a shut-off ball valve that only cuts the water to the heater, which is one thing I've been reading about.
So, this leads to a few questions.
1. Where's a really good place to get a summary of the codes that I need to worry about (other than the universal plumbing code, which I can refer to for specific code details)?
2. What pitfalls should I expect while doing this myself?
Finally, I noticed that a lot of the new Rheem heaters at Home Depot are WiFi enabled. This sounds really cool on the surface. Does anyone have experience and can comment on them? What about the fact that the water heater has a 110V powered igniter instead of a pilot light? | 2015/01/08 | [
"https://diy.stackexchange.com/questions/57466",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/31481/"
] | You should make two phone calls. The first to your local building department, which should be able to answer all your code related questions. They may even have a handout or other documentation, that outlines the requirements of replacing a water heater.
The second call should be to a local Rheem dealer, or directly to Rheem. They will be able to answer any questions you have about the equipment.
Some things to watch out for:
* Make sure you drain the old tank completely, as water can be quite heavy.
* When draining the tank, make sure you open the hot valves at fixtures. This will allow all the water to drain back to the tank.
* When opening valves at fixtures, watch out for mixing valves. These can accidentally backflow cold water through the hot water pipes, which would lead to an undrainable tank.
* If you have to install an expansion tank, make sure you charge it properly.
* Make sure you know where to dispose of the old tank, as some municipal garbage collectors will not take water tanks. | Stay away from wireless. Security and cross talk with other 2.4ghz devices being some of the problems. Hard wiring is more effort but worth it.
Its rare you will see water pressure to high. But its good to know what your pressure is regardless. |
1,670,397 | I have a large (600 odd) set of search and replace terms that I need to run as a sed script over some files. The problem is that the search terms are NOT orthogonal... but I think I can get away with it by sorting by line length (i.e. pull out the longest matches first, and then alphabetically within each length. So given an unsort set of:
```
aaba
aa
ab
abba
bab
aba
```
what I want is a sorted set such as:
```
abba
aaba
bab
aba
ab
aa
```
Is there a way of doing it by say prepending the line lenght and sorting by a field?
*For bonus marks :-) !!!
The search and replace is actually simply a case of replacing
term
with
\_term\_
and the sed code I was going to use was
s/term/\_term\_/g
How would I write the regex to avoid replacing terms already within \_ pairs?* | 2009/11/03 | [
"https://Stackoverflow.com/questions/1670397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35961/"
] | You can do this in a one-line Perl script:
```
perl -e 'print sort { length $b<=>length $a || $b cmp $a } <>' input
``` | ```
$ awk '{print length($1),$1}' file |sort -rn
4 abba
4 aaba
3 bab
3 aba
2 ab
2 aa
```
i leave you to try getting rid of the first column yourself |
1,312,438 | I'm currently trying to get a script to submit a form to a page that is external to my site but will also e-mail the answers given by the customer to me. The mail() function has worked fine for the mail... but how do I then take these values and also submit them to the external page?
Thanks for your help! | 2009/08/21 | [
"https://Stackoverflow.com/questions/1312438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140024/"
] | You could send a custom HTTP POST request from the script that you're using to send the email. Try [fsockopen](http://nl2.php.net/fsockopen) to establish the connection and then send your own HTTP request containing the data you just received from the form.
Edit:
A bit more specific. There's [this](http://netevil.org/blog/2006/nov/http-post-from-php-without-curl) example that shows you how to send a simple HTTP POST request. Just seed it with your `$_POST` array like this:
```
do_post_request(your_url, $_POST);
```
and that should do the trick. Afterwards, you could optionally evaluate the response to check whether everything went OK. | For POST, you'll need to set the external page as the processing action:
```
<form action="http://external-page.com/processor.php" method="POST">
<!-- Form fields go here --->
</form>
```
If it's GET, you can either change the form method to GET, or create a custom query string:
```
<a href="http://external-page.com/processor.php?field1=value1&field2=value2">submit</a>
```
**Edit:** I just realized you probably want to send these from within your PHP processing class. In that case, you could use set the location header with the custom query string:
```
header("Location: http://external-page.com/processor.php?field1=value1&field2=value2");
``` |
7,231,532 | I am trying to iterate over this data structure:
```
$deconstructed->{data}->{workspaces}[0]->{workspace}->{facts}[0]->{code}
```
where `fact[0]` is increasing. It's several files I am processing so the number of `{facts}[x]` varies.
I thought this might work but it doesn't seem to be stepping up the `$iter` var:
```
foreach $iter(@{$deconstructed->{data}->{workspaces}[0]->{workspace}->{facts}}){
print $deconstructed->{data}->{workspaces}[0]->{workspace}->{facts}[$iter]->{code}."\n";
}
```
I'm totally digging data structures but this one is stumping me. Any advice what might be wrong here? | 2011/08/29 | [
"https://Stackoverflow.com/questions/7231532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/488188/"
] | $iter is being set to the content of each item in the array *not* the index. e.g.
```
my $a = [ 'a', 'b', 'c' ];
for my $i (@$a) {
print "$i\n";
}
```
...prints:
```
a
b
c
```
Try:
```
foreach $iter (@{$deconstructed->{data}->{workspaces}[0]->{workspace}->{facts}}){
print $iter->{code}."\n";
}
``` | `$iter` is not going to be an index that you can subscript the array with, it is rather the current element of the array. So I guess you should be fine with:
```
$iter->{code}
``` |
4,080,667 | This is similar to [How to keep the order of elements in hashtable](https://stackoverflow.com/questions/1419708/how-to-keep-the-order-of-elements-in-hashtable), except for .NET.
Is there any `Hashtable` or `Dictionary` in .NET that allows you to access it's `.Index` property for the entry in the order in which it was added to the collection? | 2010/11/02 | [
"https://Stackoverflow.com/questions/4080667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149573/"
] | A `NameValueCollection` can retrieve elements by index (but you cannot ask for the index of a specific key or element). So,
```
var coll = new NameValueCollection();
coll.Add("Z", "1");
coll.Add("A", "2");
Console.WriteLine("{0} = {1}", coll.GetKey(0), coll[0]); // prints "Z = 1"
```
However, it behaves oddly (compared to an IDictionary) when you add a key multiple times:
```
var coll = new NameValueCollection();
coll.Add("Z", "1");
coll.Add("A", "2");
coll.Add("Z", "3");
Console.WriteLine(coll[0]); // prints "1,3"
```
The behaviour is well documented, however.
Caution: `NameValueCollection` does **not** implement `IDictionary`.
---
As an aside: `Dictionary<K,V>` does not have any index you can use, but as long as you only add elements, and never remove any, the order of the elements is the insertion order. Note that this is a detail of Microsoft's current implementation: the documentation explicitly states that the order is random, so this behavior can change in future versions of the .NET Framework or Mono. | >
> Is there any Hashtable or Dictionary in .NET that allows you to access it's .Index property for the entry in the order in which it was added to the collection?
>
>
>
No. You can enumerate over all the items in a Hastable or Dictionary, but these are not guaranteed to be in any sort of order (most likely they are not)
You would have to either use a different data structure altogether, (such as SortedDictionary or SortedList) or use a separate list to store the order in which they were added. You would want to wrap the ordered list and your dictionary/hashtable in another class to keep them synched. |
53,143,669 | I am using Yoast plugin in my WordPress website for SEO. If I uninstall it after implementing SEO, will its features be removed from my website? Features like title, meta descriptions etc. I want to uninstall to make my website faster to load. | 2018/11/04 | [
"https://Stackoverflow.com/questions/53143669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6396887/"
] | Yes, those features wil be removed (or rather: not be present anymore): They are added dynamically by the plugin when a page is loaded. So if the plugin is gone, that won't happen anymore.
If your website is static, you could copy the relevant HTML meta tags for SEO from the header while the plugin is active, insert them in your code (i.e. in the `header.php` file) and then deactivate the plugin. But you'd have to do that for every page seperately (which works against the concept of having *one* `header.php` file for all pages). But all that is rather mere theory for a Wordpress site (I wouldn't bother trying that). | First be sure that it is the Yoast plugin that is making your website slow.
* You can do this by deactivating all plugin then activating one by one until you find the plugin causing the problem.
* You can also view ways to make your website faster using this guide:
[The Ultimate Guide to Boost WordPress Speed & Performance](https://www.wpbeginner.com/wordpress-performance-speed/)
Deactivating Yoast SEO would remove all optimization done on the site as they are all loaded dynamically on page load. |
16,553,606 | In most OOP books and articles, we read something like this about constructors:
>
> A constructor is a specialized method in a class, its name is identical
> to the class name, and it has no return type.
>
>
>
So our constructor is of this form:
```
class MyClass {
public: /* no return type */ MyClass();
}
```
Well, this definition has some conflicts with OOP principles: methods must have an return type (even if `void`), and in an object, we cannot have 2 members with the same name, so a method cannot has the same name as the class's name.
I think we can change the definition to something like this one:
>
> A constructor is a specialized method in a class, it has no name – an
> anonymous or nameless method – and its return type is
> (the type of) the class.
>
>
>
So we will have:
```
class MyClass {
public: MyClass /* no method name */ ();
}
```
In the second definition: we are allowed to have anonymous methods in most OOP languages, and our method has a really return type.
```
var obj = new MyClass();
```
Constructor called, and `obj` is an instance of `MyClass`, so constructor has a return value. In the other hand, `new MyClass()` is a contract for calling an accessible anonymous method on a blueprint of an object named `MyClass`.
What do you think? Am I wrong or can we use this definition or take this perspective to looking at constructors?
**UPDATE:**
Why am I getting down and close votes? Explain please. | 2013/05/14 | [
"https://Stackoverflow.com/questions/16553606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/645167/"
] | Operator `new` does two things:
1. Allocates memory for a new object (and the pointer to that piece of memory is assigned to obj in your example).
2. Calls the constructor which initializes the object with default values.
So, in that sense, constructor doesn't return anything. It's the `new` operator that returns the object. Constructors works as a decorator: it receives a piece of memory and initializes various bytes in that memory with default values.
It also answers your first point, that the constructor must have a return type. As the constructor only initializes some data allocated by the `new` operator it can't return anything, because if it did want to return something then the expression `new MyClass()` would, in fact, have to return two types at the same time!! One type would be the object allocated by operator `new` and the second type would be the same object decorated by the constructor.
If you want to be so picky about definitions I would rather suggest changing the name `method` in the description to something else (maybe decorator, like in the design pattern?).
And who said that a method must return a type? What about abstract methods, do they return anything?
**EDIT** to answer some of the questions:
Yeah, abstract methods have a return type but they don't actually return anything, only methods which implements the interface they define. My point was to show that not everything that is defined as *method* has to return a type. Some methods (or some language constructs) do return something and some don't, regardless of how you call them.
I guess in case of constructor it was easier to define them in terms of methods that don't return anything, because they are very similar to any other regular method, apart from the very fact that they don't actually return anything, rather than trying to make up another definition for a method-like construct that don't return anything.
Operator `new` doesn't say *create an object*. It's just an operator, a language construct. When the code gets compiled `new` actually ceases to exist, it's replaced with some assembler code to allocate and initialize a piece of memory that will represent the object.
Let's disassemble the steps taken when executing `new MyClass()` one by one:
1. Operator `new` allocates a piece of memory with the size needed to store all variables and metadata of class `MyClass` with all its parent and child classes.
2. The operator now executes constructors of all the parent classes of class `MyClass` (if any).
3. The operator executes constructors of all the child classes of class `MyClass` (member variables stored in `MyClass` which are not build-in classes themselves).
4. The operator finally executes the constructor of the class `MyClass`.
5. The operator `new` returns the created object (or a pointer to the allocated piece of memory).
Very rarely there is just one constructor to execute. If the class has parent classes and holds any custom classes within then the `new` operator has to execute a few, if not dozens of constructors before being able to return the object. Where would all the return types go if each constructor had to return something, and what would be the point of doing that if we can't do anything with whatever the constructors were to return?
**What animal is an operator?**
I think what is confusing here is the definition of an operator. Operator is not a method to invoke. Thinking that `new` says to create an object is as wrong as saying that `+` says to add two objects or that `=` says to compare objects. Operators can be overloaded but the principle is that operators are language constructs that define operations the language (the compiled assemble code) performs, e.g. assign to a variable a sum of two objects, create an object, etc. See [operators on wikipedia](http://en.wikipedia.org/wiki/Operator_%28programming%29). | Who cares what descriptions of constructors are used in books? Why bother with the semantics?
The single purpose of constructors is to construct and instatiate an object, and there's no OOP without an object.
Constructors do something and don't retrun a value so that's why they are labeled by many books as "specialized methods" and the word specialized is used precisely because they don't need the void keyword in their signature.
It's quite clear what constructors do and how they do it so your question boils down to whether the constructors are properly described in literature or not, and while I happen to think they are, precisely because the word "specialized" is used, what's the point of wasting the time with that level of dissection?
If you go directly to the source (MSDN) you'll find this on constructors in C# Programming Guide:
>
> Whenever a class or struct is created, its constructor is called. A
> class or struct may have multiple constructors that take different
> arguments. Constructors enable the programmer to set default values,
> limit instantiation, and write code that is flexible and easy to read.
>
>
>
As you can see MSDN is not labeling constructors as "specialized methods" (or anything else), it is just clearly and succintly describing what a constructor is and what is its purpose. That's just a part of how they designed their framework so what metaphores are used by some authors to describe constructors is completely irrelevant...
Finally, to quote the "Framework Design Guidelines":
>
> There is no such thing as the perfect design. Design is all about
> making trade-offs, and to make the right decisions, you need to
> understand the options, their benefits, and their drawbacks. If you
> find yourself thinking you have a design without trade-offs, you are
> probably missing something big instead of finding the silver bullet.
>
>
>
Making constructors the way they are could easily be viewed as just such a trade-off as described in that quote. |
358,373 | I [see](https://i.stack.imgur.com/nX6bX.png) the following warning for Sierra wireless (cellular) modems:
>
> Do not operate the Sierra Wireless modem in any aircraft, whether the aircraft is on the ground or in flight. In aircraft, the Sierra Wireless modem **MUST BE POWERED OFF**. When operating, the Sierra Wireless modem can transmit signals that could interfere with various onboard systems.
>
>
> *Note: Some airlines may permit the use of cellular phones while the aircraft is on the ground and the door is open. Sierra Wireless modems may be used at this time.*
>
>
>
However, from what I know, the restriction on cellular communication in aircraft is (was?) an FCC regulation, not an FAA regulation–presumably because it causes trouble for cell towers on the *ground*, not for the aircraft itself.
And that makes sense: people forget to turn off their phones all the time, so it would make no sense for aircraft designers not to account for this.
Nevertheless, this warning is explicitly saying otherwise.
I was wondering, how true is this warning actually? Could such a modem really interfere with aircraft equipment, and could this actually be *airline*-dependent? Is there any history of this happening? | 2018/02/26 | [
"https://electronics.stackexchange.com/questions/358373",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/4645/"
] | Problem with SMPS is the pulse current rating is usually not much more than the average current rating, so you'll end up paying for a very powerful supply that you will only use when pushing the buttons on your pinball.
Unlike a SMPS, a transformer can be overloaded without trouble, as long as duty cycle remains low. It's heavy, so it takes a while to overheat.
The cheapest source for this sort of transformer is an old audio amplifier pulled out of a dumpster. If it's a 50W amp, wiring both secondaries in series should give close enough to 50-60V. You'll also get a few aged capacitors for free. Before stripping it for parts, look online to see if it's not a collector's model though...
Another option would be a few used 12V lead acid batteries, with a low power 48V supply as float charger. In this case the batteries are used a bit like capacitors. They don't need to be in top shape, so you could also get them for free. | A transformer is probably the simplest option. It doesn't need to be exactly "110 in 50 out". Transformers are ratiometric, so you just need about 2:1. I would get a 110 to 230v transformer and run it in reverse. 110 \* (110/230) = 52.6v. I saw some cheap, high power transformers that fit the bill on ebay.
You almost definetly can't hook up 4 atx power supplies in series, because they're probably grounded.
You may be able to use a smaller power supply, plus a cap bank. You're correct the supply will probably trip almost instantly if you overdraw it, even with a bunch of caps. The reason is that for the caps to provide power, the voltage has to drop. If the supply is any good, it's going to fight that drop and basically take the whole load itself.
The way to counteract this is to place a beefy current limiting resistor between the power supply and the caps.

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2flZTsG.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Calculating the exact resistor is actually kind of tricky. But you can just buy a handful of 1 ohm power resistors and figure it out by trial and error. You could also play around with a circuit simulation, but you'll need to know the coils inductance. I think if you click on this schematic it'll bring up circuit labs, which has a simulation feature.
Simulation of the circuit [here](https://www.falstad.com/circuit/circuitjs.html?ctz=CQAgjCAMB0l3AWAnC1b0DYQGZpgOwbYoBM2AHBmOddgiAKySMgLaMCmAtGGAFABnEOQTkcJZkjAlxzZhABmAQwA2AjnwBujJDIRwdM7BKin9rMXKjQGfAO6HZIDPiMnIfAE7hIDLMflffxEzPhUfPxwQsCDWUVMYSCQE%20xApN0DIMQCoVJisp3zsyHoPByKcEoj-KrLqyvoYyJy6pqwEePxsdvi6hl04sX69Aw9vFwyQLv93YVTpwccOy1SRbJMFlr4AYynupwXlhLwLWHhzi7B6UT4Ae3BnUtYk-BZE%20CRCPxIGUxkIbB3ViPMwvaznQgkJDEBAMbDSX7vOCfDDfX4QPQ4PhAA) |
37,290,527 | I have a scene with two cubes, and I would like to be able to only scale one cube. Basically, what I want to do is when I press the S uppercase key, the cube will continue to become larger as longer as I continue to press uppercase S, and when I press lowercase s I want to be able to make the cube smaller as long as lowercase s is pressed.
I have run into two problems:
1. I do not know how to detect whether the key pressed is lower case or upper case.
2. My entire scene (as in both cubes) enlargen and shrink when I press the keys.
Here is my code for the keys:
```
void keyPressed(GLFWwindow *_window, int key, int scancode, int action, int mods) {
// Control the state of keys pressed
if (action == GLFW_PRESS)
keys[key] = true;
else if (action == GLFW_RELEASE)
keys[key] = false;
switch (key) {
case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(_window, GL_TRUE); break;
// Change between points, lines and fill
case GLFW_KEY_P: glPolygonMode(GL_FRONT_AND_BACK, getMode('P')); break;
case GLFW_KEY_W: glPolygonMode(GL_FRONT_AND_BACK, getMode('W')); break;
case GLFW_KEY_T: glPolygonMode(GL_FRONT_AND_BACK, getMode('T')); break;
case GLFW_KEY_S: scale_matrix = scale(scale_matrix, vec3(2.0f, 2.0f, 2.0f));
//model_matrix = scale(model_matrix, vec3(2.0f, 2.0f, 2.0f));
break;
case GLFW_KEY_R: scale_matrix = scale(scale_matrix, vec3(0.5f, 0.5f, 0.5f));
//model_matrix = scale(model_matrix, vec3(0.0f, 0.0f, -1.0f));
break;
//Reset camera
case GLFW_KEY_D: cameraPosition = vec3(0.0, 0.0, 1.0);
view_matrix = lookAt(
cameraPosition,
vec3(0.0f, 0.0f, -100.0f),
vec3(0.0, 1.0, 0.0));
break;
default: break;
}
return;}
```
Since I wasn't sure on how to detect uppercase and lower case, I assigned R as the key to shrink the scene. This is the code for my cube positions:
```
glm::vec3 cubePositions[] = {
glm::vec3(0.0f, 0.0f, -1.0f),
glm::vec3(2.0f, 10.0f, -10.0f),
};
```
What I have tried so far was to use an if statement for case: GLFW\_KEY\_S to check for the cube position but that did not work. | 2016/05/18 | [
"https://Stackoverflow.com/questions/37290527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4129683/"
] | Best way to avoid unneccessary event handling is to bind the body click inside the menu click, like so:
```
//persist your current menu state
var open = false;
function clickOn() {
//force open the menu rather than toggle
//so you are in control of the state
$(".startBtn").fadeOut(200);
$("#startMnu").fadeIn(200);
open = true;
//bind the body click
$("body").on("click.menu", function(event) {
clickOff(event);
});
}
function clickOff() {
$(".startBtn").fadeIn(200);
$("#startMnu").fadeOut(200);
open = false;
//unbind the body click so it doesn't happen when the menu is closed
$("body").unbind("click.menu");
}
$(".startBtn").click(function(e) {
//stop the event bubbling up to the body
e.stopPropagation();
//check the current state
open ? clickOff() : clickOn();
});
``` | ```js
$(".startBtn").click(function() {
$(".startBtn").fadeToggle(200);
$("#startMnu").toggle(200);
});
$("body").click(function(event) {
if(!$(event.target).closest('#startMnu').length && !$(event.target).closest('.startBtn').length) {
$(".startBtn").fadeToggle(200);
$("#startMnu").toggle(200);
}
});
```
```css
.menu {
position: relative;
min-height: 60px;
}
#startMnu {
background: #ffc501;
position: absolute;
list-style: none;
width: 320px;
display: none;
padding: 0;
margin: 0;
top: 100%;
left: 0;
}
#startMnu li a {
text-decoration: none;
padding: 3px 8px;
display: block;
color: #fff;
}
#startMnu li a:hover {
background: #ffe501;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav class="menu">
<button class="startBtn">Opener</button>
<ul id="startMnu">
<li><a href="#">Menu Item 1</a></li>
<li><a href="#">Menu Item 2</a></li>
<li><a href="#">Menu Item 3</a></li>
<li><a href="#">Menu Item 4</a></li>
<li><a href="#">Menu Item 5</a></li>
</ul>
</nav>
``` |
36,922,921 | I've written a function with recursive approach to get the values from nested Array.
The problem is, I can't reset the global variable after each call. Here after every call the results are being appended to previous result instead of giving new result. I know, Global variable isn't being reset, so data will always append. But I can't define the variable inside the function as its recursive call.
How can I avoid this situation? Any help would be appreciated.
```
var res = [];
function getData(arr) {
if(!Array.isArray(arr)) {
res.push(arr);
return res;
}
for(var i = 0; i < arr.length; i++) {
getData(arr[i]);
}
return res;
}
getData([1, [2], [3, [[4]]]]); // res = [1, 2, 3, 4]
getData([[["a"]], [["b"]]]); // res = [1, 2, 3, 4, "a", "b"], expected is res = ["a", "b"];
getData([1, {}, [3, [[4]]]]);
``` | 2016/04/28 | [
"https://Stackoverflow.com/questions/36922921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4533505/"
] | >
> But I can't define the variable inside the function as its recursive
> call.
>
>
>
You can define the result variable inside the function but you need to properly deal with the return values of your recursive calls:
```
function getData(arr) {
var res = [];
if (Array.isArray(arr)) {
for (var i = 0; i < arr.length; i++) {
res = res.concat(getData(arr[i]));
}
} else {
res.push(arr);
}
return res;
}
```
(And you don't need to make the result array a parameter of the function.) | Landed up with another solution using closure, it might help someone.
```
function getData(arr) {
var res = [];
return innerGetData(arr);
function innerGetData(arr) {
if(!Array.isArray(arr)) {
res.push(arr);
return res;
}
for(var i = 0; i < arr.length; i++) {
innerGetData(arr[i]);
}
return res;
}
}
``` |
7,730 | In the opening of Fullmetal Alchemist, it says...
>
> Human kind cannot obtain anything without first giving something in
> return To obtain, something of equal value must be lost That is
> alchemy's first law of equivalent exchange. In those days, we really
> believed that to be that world's one and only truth.
>
>
>
But why did the Elric brothers believe this to be the one and only law of alchemy? If this was explained in one of the episodes of Fullmetal Alchemist or Brotherhood, please list it too, thanks. | 2014/02/27 | [
"https://anime.stackexchange.com/questions/7730",
"https://anime.stackexchange.com",
"https://anime.stackexchange.com/users/3650/"
] | Okay, so, there's a couple things in play here you need to be aware of. Keep in mind that some of this is slightly speculative.
First, it is *only in the dub* that Alphonse states it to be the "one and only" truth. The original commentary states,
>
> その頃【ころ】、ぼくらは、それが世界【せかい】の真実【しんじつ】だと信じて【しんじて】いた。
>
>
> "When we were young, we believed that to be the truth of the world."
>
>
>
Second, though, I think there is an important reason that Alphonse brings this up. Starting at episode 43, the pre-OP commentary changes to the following:
>
> He who obtains [the Philosopher's Stone] is exempt from the rule of Equivalent Exchange and does not have to sacrifice anything to obtain something.
>
>
>
*(Note: This statement is somewhat wrong: During this unusual exchange, there is still something lost, but it's not apparent to whomever it is doing the transmutation.)*
In their adventure, Ed and Al basically learned that human lives are given an alchemical value; since they both believe human life to be invaluable, this shakes the foundation of the principle of Equivalent Exchange that they grew up learning.
This seems to be the only reason that Alphonse used the past tense with "believed"; the Philosopher's Stone shattered what they believed Equivalent Exchange truly meant. To him, Equivalent Exchange can no longer be the "one and only" truth.
This idea also holds true in *Brotherhood*. The Philosopher's Stone is essentially identical, and the brothers learn the same terrible details of it. | Alchemy in the real world is recognized as a protoscience that contributed to the development of modern chemistry and medicine.
Both Ed and Al say that Alchemy is a science and that the input must be equal to their output, equivalent exchange is this because for what you give up (your input) you will recive something of equal value (your equal output)
There are 2 parts to Equivalent Exchange which can be read up on the [Wikia page](http://fma.wikia.com/wiki/Alchemy#Equivalent_Exchange), The Law of Conservation of Mass and The Law of Natural Providence. I should point out that Scar is still following The Law of Conservation of Mass as what is he doing is breaking objects apart but not reforming, when Ed goes to repair Al after getting his arm back he checks that they did pick up every tiny fragment hinting at this.
Now one can say that the Red Stones or Incomplete Philosopher's Stone can bypass however in a sense they don't, the Red Stones are created by combining materials and get used up over time thus they don't have a Rebound. the Incomplete Philosopher's Stones have the rebound because they are used to bypass Equivalent Exchange however it's unpredictable when the alchemical forces begin stabilize themselves, Marcoh and the State Alchemists during Ishval War were just lucky it never occurred during the war and after it Marcoh seemed to reduce it's usage.
The Philosopher's Stone on the other hand may be the only exception, using it one can bypass Equivalent Exchange however one needs to follow Equivalent Exchange to make one in the first place by sacrificing lives. In Brotherhood, because the first known Philosopher's Stone came from knowledge from [Dwarf](http://fma.wikia.com/wiki/Dwarf) the Philosopher's Stone may be keeping the alchemical process balanced by doing something that is beyond the realm of human understanding which only [Truth](http://fma.wikia.com/wiki/Truth) understands |
780,617 | A DFA that accepts a language in which every odd position of a string is a 1 with inputs as {0,1} | 2014/05/04 | [
"https://math.stackexchange.com/questions/780617",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/147724/"
] | You can do this in 2 states - `WAIT` and `OK`. You start in the `WAIT` state and hope to get to the `OK` state, which accepts. Here are the rules:
$$
\mathrm{WAIT} \overset{1}{\rightarrow} \mathrm{OK}
$$
$$
\mathrm{OK} \overset{0}{\rightarrow} \mathrm{WAIT}
$$
$$
\mathrm{OK} \overset{1}{\rightarrow} \mathrm{WAIT}
$$ | 
All state machines have a starting point. The top right state represents the "never going to accept" state. The bottom left state is the necessary accepting state. The other state is the "seen an even number of inputs and so far so good" state. |
5,599,391 | I know how to obtain which modifier key was pressed in C# but I don't know how I can actually check if any modifier key was pressed. I need to check it in `KeyUp` event, is it possible any other way than doing something like `if(e.KeyCode != Keys.Control && e.KeyCode != Keys.Alt && ...)` ? Thanks. | 2011/04/08 | [
"https://Stackoverflow.com/questions/5599391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678377/"
] | ```
if ((Control.ModifierKeys & Keys.Shift) != 0)
```
will help you detect whether a modifier key (e.g. `ctrl` or `shift`) was pressed.
Check the Post below for reference:
[How to detect the currently pressed key?](https://stackoverflow.com/questions/1100285/c-how-to-detect-the-currently-pressed-key/1100374#1100374) | The [KeyEventArgs](http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.aspx) class has properties that you can check. For example, to see if the Alt key was pressed, you can write:
```
if (e.Alt)
{
// Alt key was pressed
}
``` |
48,155,787 | I have the following dataframe `df`:
```
id lat lon year month day
0 381 53.30660 -0.54649 2004 1 2
1 381 53.30660 -0.54649 2004 1 3
2 381 53.30660 -0.54649 2004 1 4
```
and I want to create a new column `df['Date']` where the `year`, `month`, and `day` columns are combined according to the format `yyyy-m-d`.
Following [this post](https://stackoverflow.com/a/35921945/5110870), I did:
```
`df['Date']=pd.to_datetime(df['year']*10000000000
+df['month']*100000000
+df['day']*1000000,
format='%Y-%m-%d%')`
```
The result is not what I expected, as it starts from 1970 instead of 2004, and it also contains the hour stamp, which I did not specify:
```
id lat lon year month day Date
0 381 53.30660 -0.54649 2004 1 2 1970-01-01 05:34:00.102
1 381 53.30660 -0.54649 2004 1 3 1970-01-01 05:34:00.103
2 381 53.30660 -0.54649 2004 1 4 1970-01-01 05:34:00.104
```
As the dates should be in the `2004-1-2` format, what am I doing wrong? | 2018/01/08 | [
"https://Stackoverflow.com/questions/48155787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5110870/"
] | One solution would be to convert these columns to string, concatenate using `agg` + `str.join`, and then convert to `datetime`.
```
df['Date'] = pd.to_datetime(
df[['year', 'month', 'day']].astype(str).agg('-'.join, axis=1))
df
id lat lon year month day Date
0 381 53.3066 -0.54649 2004 1 2 2004-01-02
1 381 53.3066 -0.54649 2004 1 3 2004-01-03
2 381 53.3066 -0.54649 2004 1 4 2004-01-04
```
You may also want to add an `errors='coerce'` argument if you have invalid datetime combinations between your columns. | To fix your code
```
df['Date']=pd.to_datetime(df.year*10000+df.month*100+df.day,format='%Y%m%d')
df
Out[57]:
id lat lon year month day Date
0 381 53.3066 -0.54649 2004 1 2 2004-01-02
1 381 53.3066 -0.54649 2004 1 3 2004-01-03
2 381 53.3066 -0.54649 2004 1 4 2004-01-04
``` |
9,660 | So, I tend to run 700x23c or 700x25c tires on my commuter bike. Sometimes I'm lazy and forget to check the air pressure and inevitably get a pinch flat when I hit some stationary object, pothole, or big curb.
When I get a snakebike type of pinch flat (2 holes somewhat separated, usually on opposite sides of a ridge in the tube, I find it hard to patch.
Either I use a small patch without having the small patch only extend past the holes 1mm or 2mm and usually placed over the ridge/seam in the tube, or I use a large patch which is really hard to apply since it is wider than the tube (making it hard to apply glue and appropriate pressure to patch when gluing) but provides coverage for both holes at once.
Park tool GP-2 glueless patches seem to work ok for this situation since they can easily be overlapped without issue. However, I hear anecdotal evidence that they are not as durable as patches used with vulcanizing fluid.
What is the preferred way to patch these type of tricky flats? | 2012/05/31 | [
"https://bicycles.stackexchange.com/questions/9660",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/2997/"
] | 1. Use the thinnest conventional (tube-of-glue type) patches you can find. They should be the type with feathered edges. A little overlap is OK, but trim the edges if there will be a lot.
2. Better still, swap in your spare tube.
3. Better still, don't let your tires go flat.
(Avoid using large patches as they won't expand as the tube expands.) | I've had good luck with the Park GP-2's being extremely durable, lasting as long as the tube. Back when I was using them frequently, I think I was running somewhere in the 70-90 PSI range. |
5,790,837 | I have an application which i am going to install on Linux touch system. The touch system is not giving me the touch sound so i decided to have that feature on my application. What is the best way to do it ? I dont want to go through each and every buttons and other components and write the codes there. Is there any global way to handle that so that the sound works throughout the application when ever the screen is touched or mouse is clicked ?? | 2011/04/26 | [
"https://Stackoverflow.com/questions/5790837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402610/"
] | Take this answer:
[How can I play sound in Java?](https://stackoverflow.com/questions/26305/how-can-i-play-sound-in-java)
... and trigger the playback in the mouse click event. | Assuming that you are using the JFC/Swing toolkit, you might want to read a bit about using the [Multiplexing Look & Feel](http://java.sun.com/products/jfc/tsc/articles/multiplexing/). Even though I don't know of any ready-to-use auxiliary look and feel(s) that might fit your needs, it should be possible to write your own auxiliary look and feel which behaves as you describe above ...
... after you have created your own auxiliary look and feel make sure to start your java interpreter with the "-Dswing.auxiliarylaf=your.auxiliary.look.and.feel.Classname" parameter. |
87,860 | We have an Intel Pro 1000 PT Dual Port Server Adapter running on a WIN2K8 box housed in an offsite colo.
I recently learned that the auto-negotiated link speed is 100Mbps. When I run the diagnostic test provided by the Device Manager > [Card] > Properties window, it says that the Network Adapter is set to auto negotiate the link speed but that "...1000 Mbps has not been chosen as one of the possible speeds."
I don't see anywhere in the properties tabs that suggest any config setting like "Available link speeds."
So, this is kind of 2 questions:
1. Is it possible that if I change the link speed from auto negotiate to 1000Mbps the network card will cease to work until I go onsite and change it back?
2. Does anyone know how I can configure 1000Mbps to be one of the available link speeds for the auto negotiation?
Thanks in advance. | 2009/11/24 | [
"https://serverfault.com/questions/87860",
"https://serverfault.com",
"https://serverfault.com/users/26793/"
] | Step 1: Ensure that the switch you're plugged into is really gigabit.
Step 2: Be prepared to travel to the colo to fix this should it go dark.
My guess is that the switch port is not allowing gigabit. | Do you have the latest driver for the NIC? Is it the Intel provided driver or a Windows driver? |
42,265,063 | When i am adding multiple fragments to a FragmentTransaction and commiting after that only last fragment is added.
```
getFragmentManager().beginTransaction().add(R.id.main_container,PropertyListFragment.newInstance()).addToBackStack(null)
.add(R.id.main_container, BlankFragment.newInstance("dfghj","fghj")).addToBackStack(null)
.add(R.id.main_container,PropertyListFragment.newInstance()).addToBackStack(null)
.add(R.id.main_container, BlankFragment.newInstance("dfghj","fghj")).addToBackStack(null)
.commit();
```
Backstack count is also 1. | 2017/02/16 | [
"https://Stackoverflow.com/questions/42265063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3069261/"
] | You can't use fragment in this way you need to use just one fragment per container.
check this:
[How do I properly add multiple fragments to a fragment transition?](https://stackoverflow.com/questions/12444205/how-do-i-properly-add-multiple-fragments-to-a-fragment-transition) | Above answer is right.
You can't use fragment in this way you need to use just one fragment per container but I gave you a little help here.
You need to define at the `XML` `FrameLayout` for each `Fragment` something like this.
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="@+id/fragment_1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<FrameLayout
android:id="@+id/fragment_2"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
```
And in the `Fragment` you need to define like this.
```
FragmentManager manager = getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
ListFragment listFragment = new ListFragment();
WebFragment webFragment = new WebFragment();
trans.add(R.id.fragment_1, listFragment, "list_fragment");
trans.add(R.id.fragment_2, webFragment, "web_fragment");
trans.commit();
``` |
5,187,607 | I wish to be able to write tests like this:
```none
Background:
Given a user signs up for a 30 day account
Scenario: access before expiry
When they login in 29 days
Then they will be let in
Scenario: access after expiry
When they login in 31 days
Then they will be asked to renew
Scenario: access after acounnt deleted
When they login in 2 years time
Then they will be asked to register for a new account
```
How do I do the specflow side of the tests?
Edit: how can the same step definitions cope with both "31 days" and "2 years time" | 2011/03/03 | [
"https://Stackoverflow.com/questions/5187607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/57159/"
] | ```
> how can the same step definitions cope with both "31 days" and "2 years time"
```
If your rules need no special handling for workingday, xmas, weekend, ... you can modify @Nitro52-s answer to:
```
[When(@"they login in (\d+) days")]
public void WhenTheyLoginInDays(int daysRemaining)
{
Account.RegristrationDate = DateTime.ToDay().SubtractDays(daysRemaining);
Account.VerificationDate = DateTime.ToDay();
}
```
Maybe you can also think about reformulating the scenarios like this
```
Scenario: access before expiry
When they login on '2010-01-01'
And TodayIs '2010-01-29'
Then they will be let in
``` | Try using [Moles](http://research.microsoft.com/en-us/projects/moles/) and stub the DateTime.Now to return the same date everytime. One of the best features of Moles is the ability to turn dang near anything into a runtime delegate that you can isolate. The only drawback is that it may run slower depending on the implementation you pick (stubbed vs moled). I'm just beginning to dive into it so take my suggestion with a grain of salt. |
51,593 | Every time I open Windows Explorer it is not maximized so I have to double click on the window header.
Is there some way to have it open maximized by default? | 2009/10/06 | [
"https://superuser.com/questions/51593",
"https://superuser.com",
"https://superuser.com/users/13336/"
] | Eusing's **[Auto Window Manager](http://www.eusing.com/WindowManager/WindowManager.htm)** will do that (and a lot more useful things) for you.
>
> **Automatically maximize** or minimize or normal **all new windows you
> specify**.
>
>
> Automatically minimize all new windows
> you specify to system tray.
>
>
> Automatically keep all new windows you
> specify always on top.
>
>
> Adds several menu items to standard
> window system menu.
>
>
> Minimize the current window to system
> tray.
>
>
> Apply transparency effect from 0%
> (fully transparent) to 100% (solid)
> rate to any program in Windows
> 2000/XP/2003/Vista.
>
>
> Show window property of application,
> such as window handle, class name,
> process id etc.
>
>
> Auto Refresh Internet explorer at
> custom intervals.
>
>
>
*AWM is freeware.* | A VBscript that will do the tip #3 of @joe automatically (Windows 8+)
```
Dim WshShell
Set WshShell = createObject("Wscript.Shell")
WshShell.Run "explorer.exe"
Wscript.Sleep 2000
WshShell.AppActivate "File explorer"
WshShell.Sleep 2000
WshShell.SendKeys "+%{F4}"
Set WshShell = Nothing
```
Set `WshShell.AppActivate` to "This PC" if it is set be opened there. |
51,608,549 | I have a list:
```
list1=[[2,3],[4,5],[6,7]]
```
I want to add a single value "one" to all sublist in the list at index 2
final output should be:
```
list2=[[2,3,"one"],[4,5,"one"],[6,7,"one"]]
```
tried with:
```
for list2 in list1:
print list2.insert(2,"one")
```
But its showing error as `None`. | 2018/07/31 | [
"https://Stackoverflow.com/questions/51608549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7482017/"
] | `list.insert` is an [in-place operation](https://stackoverflow.com/questions/1516889/python-insert-not-getting-desired-results) and returns `None`. Instead, you can use a list comprehension:
```
L = [[2,3],[4,5],[6,7]]
res = [[i, j, 'one'] for i, j in L]
print(res)
[[2, 3, 'one'], [4, 5, 'one'], [6, 7, 'one']]
``` | Change your code as below :
```
list1=[[2,3],[4,5],[6,7]]
for subList in list1:
subList.append("one")
print list1
```
Output is :
```
[[2, 3, 'one'], [4, 5, 'one'], [6, 7, 'one']]
``` |
8,548,387 | I'm a C++ learner.I'm trying to code a basic C++ project. It's basic automation system . It has a navigation menu.
```
Choose an option :
1 ) Add a new customer
2 ) List all customers
...
```
There will be a `nav`variable, which containing user's choice. This is my source code :
```
#include <stdio.h>
#include <clocale>
int nav;
void main()
{
setlocale(LC_ALL,"turkish");
navigasyon();
switch (nav) // checking 'nav' variable which assigned in navigasyon()
case "1" :
printf("Now you are adding a new customer");
break;
case "2" :
printf("Now you are listing all customers");
break;
}
void navigasyon()
{
printf("Choose an option \n");
printf("1 ) Add a new customer\n");
printf("2 ) List all customers\n");
scanf("%d", &nav); // assigning '`nav' variable
}
```
In shortly,
in main() , navigasyon() will show navigation menu, user choose 1 or 2 and then navigasyon() assinging it to `nav` . Lastly checking `nav`with switch-case.
But i'm getting `'navigasyon': identifier not found` error. | 2011/12/17 | [
"https://Stackoverflow.com/questions/8548387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556169/"
] | You should declare `navigasyon` before `main`. | Place 'navigasyon' above main.
C++ demands that functions are declared before they are used. This can done by placing the whole function before the usage or by forward declaration, where you only have the signature before. |
22,859,494 | I have got the following trouble: I have installed SonarQube and Android Plugin with "Android Lint" Quality Profile. When I execute my *build.gradle* script with "Android Lint" profile, sonar-runner plugin works good, but in SonarQube I can see no matching issues found, just zero.
Nevertheless, when I include another profile –not "Android Lint"– I can see a lot of issues. Also in my android SDK when apply it's own lint I can see 157 issues. What it can be?
```
sonar - version 3.7.4;
android plugin - version 0.1
``` | 2014/04/04 | [
"https://Stackoverflow.com/questions/22859494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016020/"
] | Your `sonar.sources` property should point to the root of **AndroidManifest.xml** file. E.g. if your **AndroidManifest.xml** file is located in `src/main` then your `build.gradle` file should contain:
```
sonarRunner {
sonarProperties {
...
property "sonar.sources", "src/main"
property "sonar.profile", "Android Lint"
...
}
}
```
If you need more paths in `sonar.sources` you can put them as a comma-separated list.
You can find how Sonar Android Plugin determines whether to run the analysis in its [source code](https://github.com/SonarCommunity/sonar-android/blob/master/src/main/java/org/sonar/plugins/android/lint/AndroidLintSensor.java#L61). | **change your sonar properties like this:**
```
apply plugin: "org.sonarqube"
sonarqube {
properties {
property "sonar.projectName", "appa"
property "sonar.projectKey", "appa_app"
property "sonar.projectVersion", "1.0"
property "sonar.analysis.mode", "publish"
property "sonar.language", "java"
property 'sonar.sourceEncoding', "UTF-8"
property "sonar.sources", "./src/main"
//property "sonar.exclusions", "**/*Entity.java"
// property "sonar.exclusions", "src/main/java/com/apparkb/model/**, **/*Entity.java"
property "sonar.host.url", "http://192.168.21.33:9000"
property "sonar.login", "admin"
property "sonar.profile", "testlint"//use your quality profile instead
property 'sonar.import_unknown_files', true
property "sonar.android.lint.report", "./build/outputs/lint-results-debug.xml"
property "sonar.password", "admin"
property "sonar.java.binaries", "build/"
}
}
```
For creating lint-results-debug.xml you will have to run the below command on studio terminal:
```
./gradlew lint
```
It will generate the missing XML report. Be carful, it can generate a report for each build variant (Debug by default will generate build/outputs/lint-results-debug.xml). So you can call lintDebug, lintRelease... dependings on your build variant.
**And change the lint properties to:**
```
lintOptions { // set to true to turn off analysis progress reporting by lint
quiet true
// if true, stop the gradle build if errors are found
abortOnError false
// do not ignore warnings
warningsAsErrors true
}
```
**now if you run**
```
./gradlew sonarqube
```
you will get the results shown its actually the local file report that's actually getting hosted upon the server[](https://i.stack.imgur.com/k1a2v.png) |
236,710 | I've been wondering for some time what the best way to pass a 2d array to functions is. I know that arrays, passed to functions, decay into pointers, so `int arr[25]` would become `int *arr` inside a function. The problem is with 2d arrays, `int arr[5][5]` would not become `int **arr`. Instead I've been taught to pass it like this: `int (*arr)[5]`. The problem with that is that the final square brackets need to have a size parameter inside and it needs to be known at compile time.
I've looked around and found [this answer](https://stackoverflow.com/a/35657313/12361578) which, I believe, has the best solution. The idea is to pass the 2 dimensions separately and the location of the data. So, the function's signature would be like this:
`void print(void *arr, size_t rows, size_t cols);`
Then, we create a temporary array, which we can use conventionally, like this:
`int (*temp)[cols] = (int (*)[cols]) arr;`
I wrote some code to test this and it works.
```
#include <stdio.h>
void fill(void * arr, size_t rows, size_t cols, int val);
void print(void * arr, size_t rows, size_t cols);
int main(void) {
size_t iArr = 5, jArr = 3;
int arr[iArr][jArr];
fill(arr, iArr, jArr, 0x45);
print(arr, iArr, jArr);
return 0;
}
void fill(void * arr, size_t rows, size_t cols, int val)
{
int (*temp)[cols] = (int (*)[cols])arr;
for(size_t i = 0; i < rows; i++)
{
for(size_t j = 0; j < cols; j++)
{
temp[i][j] = val;
}
}
arr = temp;
}
void print(void * arr, size_t rows, size_t cols)
{
int (*temp)[cols] = (int (*)[cols])arr;
for(size_t i = 0; i < rows; i++)
{
for(size_t j = 0; j < cols; j++)
{
printf("%3d ", temp[i][j]);
}
putchar('\n');
}
}
```
This can also be tested [here](https://repl.it/@OlegPlachkov1/SquareSpryCleantech). I'm curious whether this will work always without errors. I tested it with all kinds of sizes and, again, no problem there. Can this be improved further? Could there be any edge cases where this breaks (checks for valid arguments or making sure the size passed doesn't exceed the stack size are omitted here, as that's not the point of this question). | 2020/02/05 | [
"https://codereview.stackexchange.com/questions/236710",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/212777/"
] | Type-wise, it is ok to go from void pointers to array pointers and back. As long as the "effective type" is an int array of the specified size. Void pointers do however have non-existent type safety, so they should be avoided for that reason.
The best way is rather to use an array and let the compiler "adjust" it to an array pointer between the lines:
```
void fill (size_t rows, size_t cols, int arr[rows][cols], int val);
```
The VLA syntax requires that `rows` and `cols` exist, so `arr` must be declared on the right side of them in the parameter list. Please note that this is still a pointer and *not* a whole VLA passed by value - we can't pass arrays by value in C.
Fixed example:
```
#include <stdio.h>
void fill(size_t rows, size_t cols, int arr[rows][cols], int val);
void print(size_t rows, size_t cols, int arr[rows][cols]);
int main(void) {
size_t iArr = 5, jArr = 3;
int arr[iArr][jArr];
fill(iArr, jArr, arr, 0x45);
print(iArr, jArr, arr);
return 0;
}
void fill(size_t rows, size_t cols, int arr[rows][cols], int val)
{
for(size_t i = 0; i < rows; i++)
{
for(size_t j = 0; j < cols; j++)
{
arr[i][j] = val;
}
}
}
void print(size_t rows, size_t cols, int arr[rows][cols])
{
for(size_t i = 0; i < rows; i++)
{
for(size_t j = 0; j < cols; j++)
{
printf("%3d ", arr[i][j]);
}
putchar('\n');
}
}
``` | One suggestion will be to put your parameters on a dedicated struct
```
struct my_array {
void *data;
size_t rows;
size_t cols;
}
```
So your functions will only have one parameter as input. |
44,201,164 | I have searched the site for an answer to my question, however the solutions have been unable to solve my problem.
My Problem is:
I have tried to add a php echo element inside of an html tag. However it is throwing off an error as seen in the screenshot. I have tried various ways to adjust this code unsuccessfully.
I should mention that it is a simple MVC application.
[screenshot](https://i.stack.imgur.com/rjKy0.jpg)
Thanks in advance for any advice. | 2017/05/26 | [
"https://Stackoverflow.com/questions/44201164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7972524/"
] | You can't separate your string like that:
```
echo 'Image' 'img src='...;
^
```
If you want to concatenate everything, use `.` or just put it all on the same string:
```
echo 'Image <img src="'. $yourVariable.'"/>'; ...
``` | Your ' and " were in the wrong spots. Also, not that it's related to your PHP erorr but you were also missing the < /> around your image.
```
echo 'Image: <img src="' . $page->image . '" alt=""/></br>';
``` |
29,171,854 | This is a simple question regarding Wordpress API /wp-json. I am querying some data filtered with certain category in Wordpress. My questions is how can I control amount of result that gets returned from my Get request... The default returns seems to return around 11 most recent results. Is there any way I can make it return only 1 (most recent), or like 100 posts. What is the minimum and maximum amount I can return. And what is the syntax for it. This is the default request I have:
```
http://thisismywebsitewherewordpresslives.com/wp-json/posts?fiter[category_name]=Some Category Name I want to query&filter[order]=ASC
``` | 2015/03/20 | [
"https://Stackoverflow.com/questions/29171854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1363876/"
] | If you're using v2 of the WordPress REST API, it looks like the current method of controlling the number of results returned is:
```
website.com/wp-json/wp/v2/posts/?per_page=100
```
Replace 100 with the desired count.
If you're using a custom post type, replace posts with the custom post type. Also make sure to set `'show_in_rest' => true` when configuring the custom post type. | My recommendation above is no longer correct. Now you'll want to use:
```
website.com/wp-json/wp/v2/posts/?filter[posts_per_page]=100
```
Change the number to retrieve more or fewer posts. Change "posts" to your custom post type if necessary and make sure to set `'show_in_rest' => true` when registering the custom post type.
**Note:** While setting the posts\_per\_page value to -1 worked in earlier beta versions of the plugin (2.0-beta13.1), it does not seem to work in the most recent versions. Now it seems you must define a value in the endpoint. |
14,145,336 | With jquery, I'm attempting to pull information from a .php file and run it in another html page.
To try this out I attempted to use this example:
<http://www.tutorialspoint.com/jquery/ajax-jquery-get.htm>
The .php file would include:
```
<?php
if( $_REQUEST["name"] )
{
$name = $_REQUEST['name'];
echo "Welcome ". $name;
}
?>
```
================ The html page code includes:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Sandbox</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// has the google object loaded?
if (window.google && window.google.load) {
google.load("jquery", "1.3.2");
} else {
document.write('<script type="text/javascript" src="http://joecrawford.com/jquery-1.3.2.min.js"><\/script>');
}
window.onload = function() {
$('#test').css({'border':'2px solid #f00'});
};
</script>
</head>
<body>
<!-- -------- Test jQuery -------- -->
<p id="test">hello jQuery</p>
<!-- -------- /end Test jQuery -------- -->
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.get(
"/testing.php",
{ name: "Zara" },
function(data) {
$('#stage').html(data);
}
);
});
});
</script>
<p>Click on the button to load result.html file:</p>
<div id="stage" >
STAGE
</div>
<input type="button" id="driver" value="Load Data" />
</body>
```
The jquery library has successfully loaded, as per the "test result".
For some reason, the contents of the "testing.php" file are not being pulled... almost as though it's linked incorrectly. Is the file linked improperly? (both the .php and .html files are in the same folder)
I even tried doing something simple, like an echo statement in the php, but still nothing was pulled from the file and published to the html page.
There might be a simple fix that you see. I appreciate your time and energy in helping me resolve this issue. Thanks in advance! | 2013/01/03 | [
"https://Stackoverflow.com/questions/14145336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1899371/"
] | >
> The files are hosted from a folder on my computer
>
>
>
This gives you two problems:
1. Browsers put pretty strict restrictions on what webpages loaded from the filesystem can do, loading other files via XMLHttpRequest is forbidden
2. PHP is a server side technology, it needs a server to work (in this context)
Host your site on a webserver. It can be one you run locally, then you can access the site via `http://localhost/etc` | Use jquery.ajax instead. Here is your HTML code
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Sandbox</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// has the google object loaded?
if (window.google && window.google.load) {
google.load("jquery", "1.3.2");
} else {
document.write('<script type="text/javascript" src="http://joecrawford.com/jquery-1.3.2.min.js"><\/script>');
}
window.onload = function() {
$('#test').css({'border':'2px solid #f00'});
};
</script>
</head>
<body>
<!-- -------- Test jQuery -------- -->
<p id="test">hello jQuery</p>
<!-- -------- /end Test jQuery -------- -->
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.ajax({
url: "testing.php",
data: { name: "Zara" },
success: function(data) {
$('#stage').html(data);
}
});
});
});
</script>
<p>Click on the button to load result.html file:</p>
<div id="stage" >
STAGE
</div>
<input type="button" id="driver" value="Load Data" />
</body>
``` |
58,802,826 | I have an html table and I want to draw an arrow from one cell to an other cell. For example like this:
[](https://i.stack.imgur.com/rbJzg.png)
How could this be done?
Example HTML:
```
<html>
<body>
<table>
<tr><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td id="end">9</td><tr>
<tr><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><tr>
<tr><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><tr>
<tr><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><tr>
<tr><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><tr>
<tr><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><tr>
<tr><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><tr>
<tr><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><tr>
<tr><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><tr>
<tr><td id="start">0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><tr>
</body>
</html>
```
If you resize the browser, the arrow should stay on the (new) start/end position. | 2019/11/11 | [
"https://Stackoverflow.com/questions/58802826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/633961/"
] | With a bit of JavasSript and CSS you can achieve this without canvas or SVG. Here is an example:
```js
function getPosition(el) {
return {
x: el.offsetLeft + el.offsetWidth / 2,
y: el.offsetTop + el.offsetHeight / 2
};
}
function getDistance(a, b) {
const from = getPosition(a);
const to = getPosition(b);
return {
//https://stackoverflow.com/a/17628488/529024
distance: Math.hypot(from.x - to.x, from.y - to.y),
angle: Math.atan2(to.x - from.x, from.y - to.y) * 180 / Math.PI,
position: {
start: from,
end: to
}
}
}
function init(){
// Get values and elements then set style
const values = getDistance(
document.getElementById("start"),
document.getElementById("end")
);
let wrapper = document.getElementById('wrapper');
let arrow = document.getElementById('arrow');
let bottom = wrapper.offsetHeight - values.position.start.y;
arrow.style.height = values.distance + "px";
arrow.style.transform = `rotate(${values.angle}deg)`;
arrow.style.bottom = bottom + "px";
arrow.style.left = values.position.start.x + "px";
}
init();
window.addEventListener('resize', function(){
init();
});
```
```css
#wrapper {
position: relative;
left: 50px;
top: 100px;
}
#arrow {
position: absolute;
width: 2px;
background-color: red;
transform-origin: bottom center;
}
#arrow::before {
position: absolute;
height: 0px;
width: 0px;
border: 6px solid transparent;
border-bottom: 8px solid red;
content: "";
bottom: 100%;
left: 50%;
transform: translateX(-50%);
}
```
```html
<div id='wrapper'>
<div id='arrow'></div>
<table>
<tr>
<td >0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td id="end">9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td id="start">0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
</div>
``` | You can use my solution not complete draw arrow yet,
let create a canvas and draw a line from two points, based on calculate of start and end point.
```
Example running: https://jsfiddle.net/tabvn/uk7hsj3a
```
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<table id="my-table">
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td id="end">9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td id="start">0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
<script type="text/javascript">
var table = document.getElementById('my-table')
var startElement = document.getElementById('start')
var endElement = document.getElementById('end')
var startPoint = {x: startElement.offsetLeft + table.offsetLeft, y: startElement.offsetTop + table.offsetTop}
var endPoint = {x: endElement.offsetLeft + table.offsetLeft, y: endElement.offsetTop + table.offsetTop}
var canvas = document.createElement('canvas')
canvas.width = table.clientWidth
canvas.height = table.clientHeight
canvas.style.position = 'absolute'
canvas.style.top = startPoint.y < endPoint.y ? startPoint.y + 'px' : endPoint.y + 'px'
canvas.style.left = startPoint.x < endPoint.x ? startPoint.x + 'px' : endPoint.x + 'px'
var ctx = canvas.getContext('2d')
ctx.beginPath()
ctx.strokeStyle = 'red'
ctx.fillStyle = 'red'
ctx.moveTo(startPoint.x - (startElement.clientWidth / 2), startPoint.y)
ctx.lineTo(endPoint.x - (endElement.clientWidth / 2), endPoint.y)
ctx.stroke()
document.body.insertBefore(canvas, table, 30)
</script>
</body>
</html>
``` |
63,771,879 | *Edit: Still have this issue.*
Visual Studio Code throws the following error:
`User model imported from django.contrib.models`
The error appears in line 2 of the following script (`models.py`).
The code is from a Django tutorial and works fine. But it is annoying that Visual Studio Code (**Pylint**) throws an error (and marks the script red).
```
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
```
Also VSC throws an error when importing a custom model, e.g. `Post`.
`from app_blog.models import Post`.
The error: **Unable to import 'app\_blog.models'**
My setup:
* Win10
* Virtual Enviroment (Python, Django, Pylint, ...)
* Django 3.1.1
* Python 3.8.5
* Pylint Django
* VSC runs Python in my VENV
Pylint settings:
```
"python.linting.pylintArgs": [
"--load-plugins=pylint_django",
"--errors-only"
],
"python.linting.pylintUseMinimalCheckers": true
```
There are the following interpreter, Interpreter No. 2 is selected.
1. Python 3.8.3 64-bit ('base': conda), `~\Anaconda3\python.exe`
2. Python 3.8.5 64-bit('venv'), `.\venv\Scripts\python.exe`
3. Python 3.8.5 64-bit, `~\AppData\Local\Programs\Python\Python38\python.exe` | 2020/09/07 | [
"https://Stackoverflow.com/questions/63771879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9838670/"
] | This is late but you can always run the following in your terminal
`pip install pylint-django`
and add this to settings.json file found in .vscode folder (assuming you're using vscode)
```
"python.linting.pylintArgs": [
"--load-plugins",
"pylint_django",
"--errors-only",
"--load-plugins pylint_django"
]
```
Hope this works for you! | An alternative (when not using the User model in the models module but in other modules) is to use `from django.contrib.auth import get_user_model`
and use `get_user_model()` where you are now using User, this will probably give errors while you do this in the models.py module, because django isn't ready getting the user model yet, it can be changed in this module |
34,348,162 | I have a dropdown that gets its items from database. The default value to be selected in this dropdown is retrieved from a cookie.
The problem is,
1. there is an empty option tag as the first option and also,
2. the default value is not selected.
There is no issue at all when I use `v1.3.16`. This happens when using `v1.2.0`. (I have to use only v1.2.0)
How to fix this.
**ASPX:**
```
<select id="ddlItems" data-ng-model="ItemId">
<option value="-1">-- All Circles --</option>
<option data-ng-repeat="item in Items" value="{{item.AreaCode}}"
data-ng-selected="item.AreaCode==ItemId">{{item.AreaName}}</option>
</select>
```
**Ctrl.js:**
```
var promise = MyFactory.GetItems();
promise.then(function (success) {
if (success.data != null && success.data != '') {
var data = success.data;
$scope.Items = data.lstItems; //bind items to dropdown
$scope.ItemId = itemIdFromCookie; //select default value
alert(itemIdFromCookie); //it pops -1
}
else {
console.log(success.data);
}
}
```
**Rendered HTML:**
```
<select id="ddlItems" data-ng-model="ItemId">
<option value="? string:"-1" ?"></option>
<option value="-1">-- All Circles --</option>
//...other options
</select>
``` | 2015/12/18 | [
"https://Stackoverflow.com/questions/34348162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3813371/"
] | router.php
```
<?=file_get_contents('php://input');
```
Start embedded server
```sh
php -S 127.0.0.0:8080 ./router.php
```
Test cURL:
```
<?php
$ch = curl_init("http://127.0.0.1:8080/");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
"Expect: 100-Continue"
]);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$fields = ["bri" => 255];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object)$fields));
$response = curl_exec($ch);
print curl_getinfo($ch, CURLINFO_HEADER_OUT);
print $response;
``` | Try this function:
```
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
``` |
4,776,786 | I have a field in which all data needs to be 13 characters in length. I would like to show a check mark image if the file name that was placed in the database is the correct number of characters (13) or show an exclamation mark image if the file name is not equal to 13 characters in length. This is what I have so far, but obviously it's not working.
```
<?php
$val1 = 13;
if (count_chars($image_id) == ($val1)) {
echo '<img src="images/icons/check.gif" />';
}
else {
echo '<img src="images/icons/exclamation.gif" />';
}
?>
``` | 2011/01/23 | [
"https://Stackoverflow.com/questions/4776786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/328310/"
] | Use [strlen()](http://php.net/manual/en/function.strlen.php). count\_chars() is for counting the number of occurances of each character in the alphabet in a string. | ```
<?php
$val1 = 13;
if (strlen($image_id) == ($val1)) {
echo '<img src="images/icons/check.gif" />';
}
else {
echo '<img src="images/icons/exclamation.gif" />';
}
?>
``` |
3,139,480 | Suppose I have two systems $A$ and $B$ that produces the numbered tiles. System $A$ produces tiles 1, 2, 3, 4, and 5 with the probabilities:
```
P(1) = 0.5
P(2) = 0.2
P(3) = 0.2
P(4) = 0.07
P(5) = 0.03
```
System $B$ produces tiles 10, 11, 12, ... 100 with the probabilities:
```
P(10) = 0.08
P(11) = 0.05
P(12) = 0.09
P(13) = 0.05
P(14) = 0.05
P(15) = 0.01
P(N) = something similarly small
```
Can I directly compare the entropy of these two systems using
$$H(X) = -\Sigma\_{i=1}^n P(x\_i)log\_2(P(x\_i))$$
Is *b-ary* entropy relevant here? Or is that something totally different? | 2019/03/07 | [
"https://math.stackexchange.com/questions/3139480",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/121142/"
] | Your `ud` definition does not match the idea behind the `ud` in the Steiner/Simons-analyses - perhaps from a correction of this you'll get some clarification.
Assume the `u` one step (on odd numbers) $a\_{k+1}=(3a\_k+1)/2$ then $a\_{k+1}$ is obviously larger than $a\_k$ and thus we may call it `u`-step because it is upwards.
(*Not* your compressed transformation!)
Assume the `d` one step (on even numbers) $a\_{k+1}=a\_k/2$ then $a\_{k+1}$ is obviously smaller than $a\_k$ and thus we may call it `d`-step because it is downwards.
*(Note there is one 1-`u`-step-cycle, but only in the negative integers $-1=(3 \cdot -1 +1)/2$)*
The trivial cycle on $1$ is by this steps-definition `ud` : $1\to2$ is up and $2\to 1$ is down.
Now we might assume some general cycle with the following up-and-downs: `uuududuuudud` and it is easy to find numerically that there is no solution in integer elements. With assumed cycles with number $N$ odd-steps (`u`) with $N$ large this becomes uneasy or impossible for availabe computing power.
So there is some idea lurking around to think about looking at "easier" subsets of cycles, or *types* of cycles - about which we could possibly say more, and more effective.
---
For instance we look first at cycles of the form `uuu...u ddd...d` which means one sequence of upward steps and then one sequence of downward steps and whether we can find a solution in integer numbers for the elements of this to make it a proper cycle. The formulae which occur with the analysis of this simpler problem give strong evidence that no such type of cycle exist - and indeed R.Steiner succeeded to prove that indeed fitting the numerical increase of one sequence of stepping upwards with the numerical decrease of one sequence of stepping downwards would never come back to the initial integer value: so no cycle of this form (of any length!) can exist.
Let's denote for shortness sequences of length $K$ of consecutive `u` by `U(K)` and sequences of length $L$ of consecutive `d` by `D(L)`. Then the so-called "1-cycle" has the form `U(K) D(L)` with any $K$ and $L$ . Of course the value $L$ must approximately match that of $K$ such that we arrive at least in the near of the initial value.
If we would actually find a combination of $K$ and $L$ such that the resulting transformation `U(K) D(L)` would transform from some $a\_1$ back to $a\_1$ again then this would be called a "1-cycle". (The trivial 1-cycle is `U(1) D(1)` satisfied by the initial element $a\_1=1$ and a "1-cycle" in the negative integers exist as `U(2) D(1)` being a cycle with $a\_1=-5$ ).
From this the "k-cycle" concept is possibly a bit more transparent:
A transformation `U(K1)D(L1), U(K2)D(L2)` would be a "2-cycle" if for any $K1,K2,L1,L2$ this would become a cycle when applied at some initial element $a\_1$
*(Again there is a solution in the* negative *integers: beginning at $a\_1=-17$ we arrive at $a\_1=-17$ again by structure `U(4)D(1), U(3)D(3)`)*
For your example with $a\_1=27$ you have given the trajectory-structure as $\qquad$ `uduuuudduduuduuudduududuuuuuduuuddddddudd`
but this is not meant with the `u`'s and `d`'s according to the "k-cycle"-idea. The structure should have been described with the indicated correct interpretation of `u` and `d` as at the top of my answer which would then give
$\qquad$ `uud uuuuud ud uud uuud uuuud udd uuud uud uuuuuudd uuuuddd ud ud uddd udd uuudddd uddd`
and which would become
`U(2)D(1), U(5)D(1), U(1)D(1), U(2)D(1), U(3)D(1), U(4)D(1), U(1)D(2), U(3)D(1), U(2)D(1), U(6)D(2), U(4)D(3), U(1)D(1), U(1)D(1), U(1)D(3), U(1)D(2), U(3)D(4), U(1)D(3)`.
*Numerically this would be
$\qquad \small{ 27}$ $ \small{ \nearrow 41 \nearrow 62 \searrow 31 \\
\nearrow 47 \nearrow 71 \nearrow 107 \nearrow 161 \nearrow 242 \searrow 121\\ \nearrow 182 \searrow 91 \\
\nearrow 137 \nearrow 206 \searrow 103 \\
\nearrow 155 \nearrow 233 \nearrow 350 \searrow 175 \\
\nearrow 263 \nearrow 395 \nearrow 593 \nearrow 890 \searrow 445 \\
\nearrow 668 \searrow 334 \searrow 167 \\
\nearrow 251 \nearrow 377 \nearrow 566 \searrow 283 \\
\nearrow 425 \nearrow 638 \searrow 319 \\
\nearrow 479 \nearrow 719 \nearrow 1079 \nearrow 1619 \nearrow 2429 \nearrow 3644 \searrow 1822 \searrow 911 \\
\nearrow 1367 \nearrow 2051 \nearrow 3077 \nearrow 4616 \searrow 2308 \searrow 1154 \searrow 577 \\
\nearrow 866 \searrow 433 \\
\nearrow 650 \searrow 325 \\
\nearrow 488 \searrow 244 \searrow 122 \searrow 61 \\
\nearrow 92 \searrow 46 \searrow 23 \\
\nearrow 35 \nearrow 53 \nearrow 80 \searrow 40 \searrow 20 \searrow 10 \searrow 5\\
\nearrow 8 \searrow 4 \searrow 2 \searrow 1} $.
Note the occurence of the even numbers in that so-defined trajectory.*
Having 17 pairs of `U()D()` this ***would be*** a "17-cycle" if it ***were a cycle at all*** : if it were transforming from $27 \to 27$. But actually it transforms $27 \to 1$.
So to be able to mention something about this "hilliness" of a trajectory (which happen to *not* to close up to become a cycle) one could introduce the term *"k-trajectory"* or even better because more explicite *"k-peak-trajectory"*.
So your examples in the comment were **"2-peak-trajectories"** (because they do not cycle)
The impressive work that Simons/deWeger have done was to prove, that this structure cannot form a cycle in integers ***with any combination of $K$'s and $L$'s*** that you like to try. (Of course the sum of all $K$ is the number of odd-steps, which I usually denote by $N$)
Due to their work we know that a possible nontrivial cycle must have a structure of `U()D(),...,U()D()` with more than $72$ pairs of $U()D()$ .
---
Perhaps a more enlightening treatize is this very basic (and old, and amateurish, my sorry...:) ) [on my webspace](http://go.helms-net.de/math/collatz/aboutloop/collloopintro_main.htm) about the concept of k-cycles. | Here is an excerpt of the original work of Simons/de Weger in 2005 (pg 55). $K$ means here the number of odd steps $(3x+1)/2$ , $L$ the number of even steps $x/2$ . Perhaps this is more enlighting what "m-cycles" or "k-cycles" and "68-cycle" and "72-cycle" could mean:
[](https://i.stack.imgur.com/h8aQL.png)
Because we have higher lower bounds for $x\_\min$ meanwhile, more "m-cycles" might be disprovable/disproved now (likely something for "m" in between $73$ and $90$. |
13,713,528 | This question looks quite similar to [this one](https://stackoverflow.com/questions/11786023/how-to-disable-double-click-zoom-for-d3-behavior-zoom), but I am still not able to figure out whether it is possible to use d3.behavior.zoom but without the pan ability. In other words I just want to zoom-in/out using the wheel only.
The reason for this is that I want to be able to brush on the "zoomable" area.
Thanks! | 2012/12/04 | [
"https://Stackoverflow.com/questions/13713528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/623492/"
] | I guess it would be good sharing the workaround I found to deal with this problem. What I did is to use the listener on the start of the brush to "deactivate" the zoom:
```
zoom.on("zoom",null);
selection.call(zoom);
```
and activate it again on the *brushend* event.
There is one more trick to take into account and comes from the fact that it is important to save the *scale* and *transition* values of the last valid zoom interaction, so that you use those values when activating the brush on the *brushend* event like this
```
zoom.scale(lastEventScale).translate(lastEventTranslate).on("zoom",drawZoom);
selection.call(scatterZoom);
```
I would love hearing other more "elegant" solutions to this problem. | One solution that I found was to stick a rect element in front of the zoom-enabled element (they must be siblings) and set its fill to 'transparent', when I wanted to disable zoom interaction or to 'none', when I wanted to enable zoom interaction. It looked something like this:
```
if (chart._disableZoom) {
var rootPanel = d3.select('.rootPanel'); // this is the parent of the element that can be zoomed and panned
if (!rootPanel.select('.stopEventPanel').node()) { // create panel if it doesn't exist yet
//.stopEventPanel is appended next to the zoom-enabled element
rootPanel.append('rect').attr('class', 'stopEventPanel').attr('width', renderConfig.width).attr('height', renderConfig.height).attr('fill', 'transparent');
} else { // disable zoom and pan
rootPanel.select('.stopEventPanel').attr('fill', 'transparent');
}
} else { // enable zoom and pan
d3.select('.rootPanel').select('.stopEventPanel').attr('fill', 'none');
}
``` |
21,290,841 | I need to automate adding images to some existing posts via Craigslist API.
The documentation at <http://www.craigslist.org/about/bulk_posting_interface> states:
***Note: If you submit a posting item with the same rdf:about as an existing posting item, the existing posting item will not be updated. Presently the only way to alter the content of a posting is via URL specificed in the cl:postingManageURL element.***
This is pretty vague. The way I understand this is, you first have to attempt a post, get a URL back and then it's unclear what to do next.
Has anyone tried this? Ideas?
Thanks, Andy | 2014/01/22 | [
"https://Stackoverflow.com/questions/21290841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2540450/"
] | If we go through the different points you mentioned:
* ***I am working a problem where multiple applications need to share classes loaded by each other:*** put the classes in a common classloader at the server level, and remove them from the WARs WEB-INF/libs to avoid that WAR classes hide server classes. For example in the case of Tomcat put the jars in `$TOMCAT_HOME/lib`.
* **why this not a good idea:** This is usually not a good idea and we should only put at the server level the minimum amount of classes needed, to avoid problems due to static variables (linked to the class) to be unintentionally shared accross applications, increased possiblity of class cast exceptions, etc.
* ***So I have started by creating a separate application and putting all the common libraries in it:*** This won't work as you expect, the classes in one WAR application's WEB-INF/lib are isolated and not visible in classes in another WAR. So creating a separate application is not the way to achieve this, but installing the classes at a classloader at the server level.
* ***I am trying to find out its possible to load all classes under WEB-INF/lib/*.jar as soon the war is deployed:\*** This is not foreseen in servlet containers, see this [answer](https://stackoverflow.com/questions/677739/preloading-java-classes-libraries-at-jar-startup) for a way to do this using Java code. The reason this feature is not available is that the JVM loads the classes lazily when they are needed by other classes, and no upfront loading is done in order to save memory.
The moment when the loading of the classes occurs is best left to the inner workings of the JVM, where many optimizations are in place to load classes in the most efficient way and avoid perm gen issues.
If this does not answer the questions can you let us know what your use case is for needing to load classes upfront, we might be able to provide some alternative for what you are trying to implement - like increasing timeouts for initial requests, etc. | If you are trying to share libs within multiple web apps you need to let these libs inside JBOSS's shared library folder. JBOSS will load then at startup.
See this:
[Where to put a shared library in JBoss AS 5?](https://stackoverflow.com/questions/2108975/where-to-put-a-shared-library-in-jboss-as-5)
It's not possible for a webapp access another webapp classloader.
The app classloader, has access to 3 classloaders:
1. Its own classloader
2. Container classloader
3. Bootstrap classloader(which loads the Java SDK classes). |
71,581,892 | **How can I improve this matrix inverse calculator**
I made this matrix inverse calculator and it works fine but i want to know how can this program be made shorter.Thanks
```
from numpy import *
#inverse calculator
print(array([['a,b,c'],['d,e,f'],['g,h,i']]))
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
d = int(input("d: "))
e = int(input("e: "))
f = int(input("f: "))
g = int(input("g: "))
h = int(input("h: "))
i = int(input("i: "))
x = array([[a,b,c],[d,e,f],[g,h,i]]) #we made matrixform
#print(x)
det = linalg.det(x) # we take determinant to check if it is 0 or not
if det != 0: #if its not 0 then inverse is possible
inverse = linalg.inv(x)
print("So the inverse of matrix \n",x, "is \n", inverse)
else: #if it is 0 then print this:
print(".\n .\n Matrix is singular,\n Inverse can not be calculated")
``` | 2022/03/23 | [
"https://Stackoverflow.com/questions/71581892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17761196/"
] | Do something like:
```
public void RemoveLastRowOf5()
{
for(int i=1; i<=5 && textboxes.Count>0; i++) {
textboxes.Pop().Dispose();
}
}
```
>
> may i know after i save it in the database. how to clear the dynamic
> textboxes user input?
>
>
>
This is a disadvantage to using the `Stack`. You'd have to pop everything into another structure, clearing as you go, then put them back in the stack. If you used a List instead, you could access it like a Stack but also be able to iterate over the contents without removing them.
Here's an example of clearing:
```
public void ClearAll()
{
Stack<TextBox> temp = new Stack<TextBox>();
while(textboxes.Count>0) {
TextBox tb = textboxes.Pop();
tb.Clear();
temp.Push(tb);
}
while(temp.Count>0) {
textboxes.Push(temp.Pop());
}
}
```
There are other ways to do this. | ```
public void RemoveLast()
{
int count = 0;
while (textboxes.Count > 0 && count < 5) // the count of TextBox that you want to delete
{
TextBox tb = textboxes.Pop();
this.Controls.Remove(tb);
tb.Dispose();
count++; // my mistake.. I modified.
}
}
```
I think you want to do this. |
25,754,099 | In PHP, I have a class that takes in a function object and calls that function in a thread: [see the answer to this question](https://stackoverflow.com/questions/25186885/thread-wrapper-class-for-a-function-with-variable-arguments-in-php/25575182#25575182).
It works well with anonymous functions, however, I want to use this functionality with a static function of a different class:
```
$thThread = new FunctionThreader(OtherClass::static_function, $aParams);
```
This throws an error `Undefined class constant static_function on line x`
I have tried:
```
$fFunction = OtherClass::static_function;
$thThread = new FunctionThreader($fFunction, $aParams);
```
And I get the same error.
So is there anyway to store this static function into `$fFunction`or to simply reference it as a function object? | 2014/09/09 | [
"https://Stackoverflow.com/questions/25754099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2386432/"
] | In PHP you would usually use a [callback](http://php.net/manual/de/language.types.callable.php) for this:
```
$callback = array('ClassName', 'methodName');
$thThread = new FunctionThreader($callback, $aParams);
```
---
If `FunctionThreader::__construct()` does only accept a `Closure` and you have no influence on it's implementation, then you can wrap the static function call in a `Closure`:
```
$closure = function() { return ClassName::methodName(); };
$thThread = new FunctionThreader($closure, $aParams);
``` | You could define a lambda function which calls your static function. Or simply store function name as a string in that variable. You would also have to implement a handler code for the class that calls a function from variable.
Resources:
<http://php.net/manual/en/function.forward-static-call-array.php>
<http://ee1.php.net/manual/en/function.func-get-args.php>
Example for anonymous function:
```
<?php
$function = new function(){
return forward_static_call_array(['class', 'function'], func_get_args());
};
?>
```
Testes this, works flawlessly. |
32,634,489 | I am wondering if there is a way to setup a static IP address to a virtual machine (VirtualBox) hosted on a GCE VM instance (as a VM host).
I want to run two VirtualBox VMs on my GCE VM instance and I want to access them publicly. | 2015/09/17 | [
"https://Stackoverflow.com/questions/32634489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4974383/"
] | Yes, you can do this, but you should also consider whether you want the additional overhead of running one virtual machine (VirtualBox) inside of another virtual machine (GCE VM). Running directly on GCE VMs would be more efficient and you can easily create/destroy/control these VMs via Google Cloud Platform APIs.
In addition, if you are already using an automation framework for your VirtualBox VMs such as [Vagrant](https://www.vagrantup.com/), note that [Vagrant natively supports GCE VMs](https://github.com/mitchellh/vagrant-google), so with a few changes to your configuration, you can use Vagrant to create/modify/connect/destroy your GCE VMs as easily as you would local VirtualBox VMs.
As an alternative to static external IPs, consider also using a domain name mapping to ephemeral external IP(s) of your instance(s). You can use [Google Cloud DNS](https://cloud.google.com/dns/) to manage your DNS mappings.
For more info on static external IPs, see the [docs](https://cloud.google.com/compute/docs/instances-and-network#reservedaddress):
>
> ### Static external IP addresses
>
>
> If you need a static external IP address that is assigned to your project and persists until you explicitly release it, you can reserve a new static external IP address or promote an ephemeral external IP address to a static external IP address. Use `gcloud compute` with the [`addresses create`](https://cloud.google.com/sdk/gcloud/reference/compute/addresses/create) command or make a PUT request to the appropriate regional Addresses collection to reserve a static external IP address.
>
>
> Static external IP addresses assigned to instances are a regional resource and you must select the region where the IP address will belong to when you create the address.
>
>
> [...]
>
>
> ### Restrictions
>
>
> Static external IP addresses can only be used by one resource at a time. You cannot assign a static external IP address to multiple resources.
>
>
> There is no way to tell whether an IP address is static or ephemeral after it has been assigned to a resource, except to compare the IP address against the list of static external IP addresses reserved to that project. Use the [`addresses list`](https://cloud.google.com/sdk/gcloud/reference/compute/addresses/list) sub-command to see a list of static external IP addresses available to the project.
>
>
>
Note that static external IPs also come with some [cost](https://cloud.google.com/compute/pricing#ipaddress):
>
> ### IP address pricing
>
>
>
> ```
> Type Price/Hour
>
> Static IP address (assigned but unused) $0.01
> Static IP address (assigned and in use) No charge
> Ephemeral IP address (attached to instance or forwarding rule) No charge
>
> ```
>
> | I solved that issue to in 2 steps:
First delete the current possible ephimeral ip configuration:
=============================================================
```
gcloud compute instances delete-access-config <instance> --access-config-name "External NAT"
```
Where `<instance>` is the name of the instance you want to update, and **External NAT** is the name of the configuration, which probably has that value because of its the default one. And you can check it running this:
gcloud compute instances describe --zone=us-west1-a
And add the static one
======================
If you want to bind an static address, probably to bind it to a DNS address, execute something like this
```
gcloud compute instances add-access-config <instance> --access-config-name="External NAT" --address=xxx.xxx.xxx.xxx
```
Remember to always append the `--zone` to any **gcloud** command to avoid any ambiguity. You can get the `address` from the valid addresses configuration you have in your project, which you can be gotten like this:
```
gcloud compute addresses list
```
Dont use the `NAME` but the `ADDRESS`. You should pick an address in the same zone of your instance. When the address be attached you will see that in the `STATUS` field of the last query it will say **IN USE**.
Et voila! |
3,827 | [Shadowing](http://www.foreignlanguageexpertise.com/foreign_language_study.html#svd) is a technique for improving pronunciation popularised by the polyglot [Alexander Arguelles](http://www.foreignlanguageexpertise.com/about.html). There are many YouTube videos about the technique; most of them don't demonstrate shadowing in the way it was described by Arguelles. A very popular example (by number of views) is Julian Northbrook's video [How to improve your English Speaking and Fluency: SHADOWING](https://www.youtube.com/watch?v=GVWFGIyNswI).
In the YouTube video [SHADOWING: Revisited (watch before you try ...)](https://www.youtube.com/watch?v=QdO_0c4CsvQ), the Bulgarian language teacher Vladimir Skenderoff criticises the technique and claims that it **"is mainly recommended for interpreter trainees"**, so it is only really appropriate for **very advanced learners of a foreign language**. The statement about interpreter trainees comes from a comment on one of his videos, so it does not come from what I consider a reliable source. So my question is: Is it true that shadowing is a technique for interpreter trainees? Obviously, I am looking for answers based on **reliable sources**. | 2018/10/01 | [
"https://languagelearning.stackexchange.com/questions/3827",
"https://languagelearning.stackexchange.com",
"https://languagelearning.stackexchange.com/users/800/"
] | I think shadowing is definitely not just for interpreters trainees. My source is the [video](https://www.youtube.com/watch?v=130bOvRpt24) that Professor Alexander Arguelles made. He clearly intends it to be used by beginners for the purpose of learning a language from scratch, and talks about Shadowing generally for the first 20 minutes, after which he dives into the details of how you could use the technique together with Assimil. Indeed, this is the method that he used to learn countless languages. That is not to say that shadowing shouldn't ALSO be used by interpreter trainees. And it's also not to say that shadowing (or any specific technique) is for everybody. | The article [1], from 1997, states that although shadowing is still occasionally used, it is not considered a good method. In the book [2], from 2003, it is briefly mentioned that
>
> The move away from prescriptivism in interpreter training has led to the inclusion of activities such as the use of shadowing in training for simultaneous, simultaneous into B languages, the interpretation of non-spontaneous speech, the use in class of recorded source speeches and recognition of the link between translation and interpreting, all previously rejected or restricted by the ESIT model.
>
>
>
The book [3], from 2016, contains a longer discussion; see especially <https://books.google.no/books?id=anxwCwAAQBAJ&lpg=PT10&ots=5HOsS9gMHM&lr&hl=no&pg=PT253#v=onepage&q=shadowing&f=false>. It claims, with references, that the issue of using or not using shadowing divides the community and provides a longer discussion of the matter, with references.
One might want to check the scholarly works that cite these via Google scholar or another similar service.
Unfortunately, most of the content is behind a paywall. The legal means of accessing such documents include trying to find legally available versions of the documents via google scholar, Unpaywall extension, etc., visiting a local (university) library, and asking the authors. Asking for more details about this would be on topic at academia.SE, if it has not been done already.
[1] Déjean Le Féal, Karla "Simultaneous Interpretation with "Training Wheels"". Meta 42, no. 4 (1997): 616–621. <https://doi.org/10.7202/003453ar>
[2] Baker, M. (2003). Routledge encyclopedia of translation studies. Routledge.
[3] Pöchhacker, Franz. Introducing interpreting studies. Routledge, 2016. |
3,609,918 | I am trying to set the [Template](http://msdn.microsoft.com/en-us/library/aa372070(v=VS.85).aspx) property in the Summary Information Stram but whatever I do, it fails. I can read the property from the handle but can't write it back.
I want to generate multilingual copies of the MSI which is built (candled and light) in English. I am able to replace all the respective translated data in all the tables; the only thing I can not change is the Template property above.
I have tried all the ways I can use to pass the new String value, but it always says invalid parameter.
Here's the function I am using to do the same (C#):
```
public Boolean ChangeTemplateSummaryProperty(String strLangID) {
IntPtr hSIHandle;
if (MsiError.Success == MsiInterop.MsiGetSummaryInformation(IntPtr.Zero, m_strMSIPath, 1, out hSIHandle))
{
VariantType vtType = VariantType.LPStr;
int iVal = 0;
FILETIME oFileTime;
oFileTime.HighDateTime = 0;
oFileTime.LowDateTime = 0;
int iValSz = 0;
MsiError err = MsiInterop.MsiSummaryInfoGetProperty(hSIHandle, (uint)(SummaryInformationStreamProperty.Template),
out vtType, out iVal, out oFileTime, String.Empty, ref iValSz);
String strValue = new String('l', ++iValSz);
if (err == MsiError.MoreData)
{
err = MsiInterop.MsiSummaryInfoGetProperty(hSIHandle, (uint)(SummaryInformationStreamProperty.Template),
out vtType, out iVal, out oFileTime, strValue, ref iValSz);
}
else
{
Logger.LogError("Failed to get SummaryInformationStreamProperty.Template... err = " + err);
}
//I get the correct value here. as ";1033\0"
Logger.LogInfo("SummaryInformationStreamProperty.Template: " + strValue);
char[] arrNV = new char[strLangID.Length+2];
arrNV[0] = ';';
for (int i = 1; i < strLangID.Length + 1; i++) {
arrNV[i] = strLangID[i-1];
}
arrNV[strLangID.Length+1] = '\0';
String strNewVal = new String(arrNV);
//tried this, but fails.
//string strNV = ";";
//string strNV2 = strNV.Insert(1, strLangID);
//strNV2 = strNV2.Insert(strLangID.Length + 1, "\0");
err = MsiInterop.MsiSummaryInfoSetProperty(hSIHandle, (uint)(SummaryInformationStreamProperty.Template),
vtType, iVal, oFileTime, strNewVal);
if (err != MsiError.NoError)
{
Logger.LogError("Failed to set SummaryInformationStreamProperty.Template... err = " + err);
MsiInterop.MsiSummaryInfoPersist(hSIHandle);
MsiInterop.MsiCloseHandle(hSIHandle);
return false;
}
MsiInterop.MsiSummaryInfoPersist(hSIHandle);
MsiInterop.MsiCloseHandle(hSIHandle);
}
else
{
Logger.LogError("Failed to MsiGetSummaryInformation...");
return false;
}
return true;
}
``` | 2010/08/31 | [
"https://Stackoverflow.com/questions/3609918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/219323/"
] | Get rid of the MsiInterop that you are using and use the interop found in WiX's DTF. The Microsoft.Deploymnet.WindowsInstaller namespace has a SummaryInformation Class that exposes a read/write string Template property. Way better object model and interop without worrying about all the P/Invoke details that your current interop makes you deal with.
I'm home now so here's a code snippet:
```
using Microsoft.Deployment.WindowsInstaller;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using( var database = new Database(@"C:\orca.msi", DatabaseOpenMode.Direct ))
{
database.SummaryInfo.Template = "Intel;666";
}
}
}
}
```
Notice the use of the using() clause. The Database class implements the IDisposable interface and automatically handles ( pun intended ) cleaning up all those pesky unmanaged handles for you. | ```
Database msidb = objInstaller.OpenDatabase(MSIFileNameWithPath,MsiOpenDatabaseMode.msiOpenDatabaseModeTransact);
SummaryInfo info = msidb.get_SummaryInformation(1);
info.set_Property(2, (object)("sample title"));
info.Persist();
msidb.Commit();
```
The best reference to answer this is in detail is
<https://learn.microsoft.com/en-us/archive/blogs/mwade/sail-away-with-me-to-another-world> |
2,677,903 | I have to strip a file path and get the parent folder.
Say my path is
```
\\ServerA\FolderA\FolderB\File.jpg
```
I need to get
1. File Name = File.jog
2. Folder it resides in = FolderB
3. And parent folder = FolderA
I always have to go 2 levels up from where the file resides.
Is there an easier way or is a regular expression the way to go? | 2010/04/20 | [
"https://Stackoverflow.com/questions/2677903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/321628/"
] | ```
string fileName = System.IO.Path.GetFileName(path);
string parent = System.IO.Path.GetDirectoryName(path);
string parentParent = System.IO.Directory.GetParent(parent);
``` | Check out the Directory class (better choice than DirectoryInfo in this case). It does everything you need. You should not use a regex or any other parsing technique. |
7,617,639 | I have a PHP array of numbers, which I would like to prefix with a minus (-). I think through the use of explode and implode it would be possible but my knowledge of php is not possible to actually do it. Any help would be appreciated.
Essentially I would like to go from this:
```
$array = [1, 2, 3, 4, 5];
```
to this:
```
$array = [-1, -2, -3, -4, -5];
```
Any ideas? | 2011/10/01 | [
"https://Stackoverflow.com/questions/7617639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/903346/"
] | An elegant way to prefix array values (PHP 5.3+):
```
$prefixed_array = preg_filter('/^/', 'prefix_', $array);
```
Additionally, this is more than three times faster than a `foreach`. | I had the same situation before.
### Adding a prefix to each array value
```
function addPrefixToArray(array $array, string $prefix)
{
return array_map(function ($arrayValues) use ($prefix) {
return $prefix . $arrayValues;
}, $array);
}
```
### Adding a suffix to each array value
```
function addSuffixToArray(array $array, string $suffix)
{
return array_map(function ($arrayValues) use ($suffix) {
return $arrayValues . $suffix;
}, $array);
}
```
Now the testing part:
```
$array = [1, 2, 3, 4, 5];
```
`print_r(addPrefixToArray($array, 'prefix'));`
### Result
```
Array ([0] => prefix1 [1] => prefix2 [2] => prefix3 [3] => prefix4 [4] => prefix5)
```
`print_r(addSuffixToArray($array, 'suffix'));`
### Result
```
Array ([0] => 1suffix [1] => 2suffix [2] => 3suffix [3] => 4suffix [4] => 5suffix)
``` |
434,024 | In R I've typed the following code to get my scatterplots but the plots are all very bunched up:
[](https://i.stack.imgur.com/L6QuT.png)
```
par(mfrow=c(1,2),mai=c(0.8,0.8,2,0.8));
plot(x,y,"",cex.lab=0.5,cex.axis=0.5)
plot(log(x),y,cex.lab=0.5,cex.axis=0.5,)
```
How can I modify my code to get better scatterplots? | 2019/10/31 | [
"https://stats.stackexchange.com/questions/434024",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/243542/"
] | The `hexbin` package: my quick and painless go-to for visualizing overplotted data sets.
```
library(hexbin)
set.seed(4321)
x.axis <- c(rnorm(2000), rnorm(2000, 4, 2))
y.axis <- c(rnorm(2000), rnorm(2000, 2, 3))
point.map <- cbind(x.axis, y.axis)
# Square plot region
par(pty = "s")
# Standard R plot
plot(point.map)
```
[](https://i.stack.imgur.com/2sgXU.png)
```
# Convert coordinate data into a hexbin object
point.map.hex <- hexbin(point.map)
# Plot hexbin object with perceptually linear color ramp
plot(point.map.hex, colramp = heat.ob)
```
[](https://i.stack.imgur.com/zShHN.png) | **One way to better visualize bivariate relationships is shown below. I will use `iris` data an example**
[](https://i.stack.imgur.com/sK9rc.png)
```
# install.packages("PerformanceAnalytics")
library("PerformanceAnalytics")
my_data <- iris[, c(1,3,4)] # note 1,3,4 refer to variables in your dataset
chart.Correlation(my_data, histogram=TRUE, pch=19)
```
**As depicted on the plot:**
On the lower triangle, you see bivariate plots with a smoothing line.
On the upper triangle, you can see the actual correlations and the extent to which they are statistically significant (\* *p<.05*; \*\* *p<.01*; \*\*\* *p<.001* \*)
You do not necessarily need histograms, so you could set
`histogram=FALSE` if you like |
54,167,792 | I need to achieve something similar to: [Checking if values in List is part of String](https://stackoverflow.com/questions/16046146/checking-if-values-in-list-is-part-of-string) in spark. I.e. there is a dataframe of:
```
abcd_some long strings
goo bar baz
```
and an Array of desired words like `["some", "bar"]`.
An UDF with this code would work just fine, however, I would like to have something more efficient. Is there a way to express the `FILTER my_col CONTAINS ONE OF [items]` using the SQL DSL? Perhaps by dynamically constructing a REGEX?
>
> NOTE: it is not an exat match rather a regular 'CONTAINS' / LIKE '%thing%'. I.e. not an exact match. Otherwise the `isIn` operator would work.
>
>
>
edit
====
probably generating some SQL code dynamically is the most efficient way.
```
def orFilterGeneratorMultiContains(filterPredicates:Seq[String], column:String):Column = {
col(column).contains(filterPredicates(0)) or col(column).contains(filterPredicates(1)) // TODO iterate
}
def filterToDesiredApps(filterPredicates:Seq[String], column:String)(df:DataFrame):DataFrame={
df.filter(orFilterGeneratorMultiContains(filterPredicates, column))
}
```
So is need to still figure out how to properly iterate the expression.
edit 2
======
However, this turns out to be a bit tricky:
```
import org.apache.spark.sql.functions.col
val column = col("foo")
val interstingTHings = Seq("bar", "baz", "thing3")
interstingTHings.foldLeft(column) { (filteredOrColumnExpression, predicateItem) =>
// TODO how to properly nest the OR operator?
// filteredOrColumnExpression.contains(predicateItem) // generates: Contains(Contains(Contains('foo, bar), baz), thing3)
filteredOrColumnExpression or filteredOrColumnExpression.contains(predicateItem) // generates: ((('foo || Contains('foo, bar)) || Contains(('foo || Contains('foo, bar)), baz)) || Contains((('foo || Contains('foo, bar)) || Contains(('foo || Contains('foo, bar)), baz)), thing3))
// TODO but what y really would need is:
// col(column).contains("bar") or col(column).contains("baz") or col(column).contains("thing3")
}.explain(true)
```
as it does not generate the correct `OR` nested filter conditions. | 2019/01/13 | [
"https://Stackoverflow.com/questions/54167792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2587904/"
] | You have the right idea, but I think you want to use `||` not `or`. Something like:
```
def orFilterGeneratorMultiContains(filterPredicates:Seq[String], column:String): Column = {
val coi = col(column)
filterPredicates.map(coi.contains).reduce(_ || _)
}
``` | Wouldn't [rlike](https://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/sql/Column.html#rlike(java.lang.String)) work in this case?
```
df.filter(col("foo").rlike(interestingThings.mkString("|"))
``` |
41,274,067 | I have a class that is derived from two identical bases:
```
class Vector3d {...};
class Position:public Vector3d {...};
class Velocity:public Vector3d {...};
class Trajectory:public Position, public Velocity
{
Vector3d &GetPosition(void);
Vector3d &GetVelocity(void);
};
```
I would like to have a member functions in derived class to quickly cast to one or the other base. What I am trying is:
```
Vector3d &GetPosition(void) const
{
return static_cast<const Vector3d &>(*this);
}
```
but I received a kind message from the compiler: "Reference initialized with 'const Position', needs lvalue of type 'Vector3d'"
When I use:
```
const Vector3d &GetPosition(void) const
{
return static_cast<const Vector3d &>(*this);
}
```
things compile ok but I cannot use it in the way that I intend:
```
Trajectory t;
t.Position=Set(20,30,50);
```
because t.Position is const and hence an improper lvalue, as the compiler announces.
Any ideas on how to reference base classes from this into a non constant dereference? | 2016/12/22 | [
"https://Stackoverflow.com/questions/41274067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7328061/"
] | You might do
```
class Trajectory:public Position, public Velocity
{
public:
Vector3d &GetPosition() { return static_cast<Position&>(*this); }
Vector3d &GetVelocity() { return static_cast<Velocity&>(*this); }
};
```
[Demo](http://ideone.com/uSzgAp)
but using composition instead of inheritance seems more appropriate.
```
class Trajectory
{
public:
const Position& GetPosition() const { return position; }
Position& GetPosition() { return position; }
const Velocity& GetVelocity() const { return velocity; }
Velocity& GetVelocity() { return velocity; }
private:
Position position;
Velocity velocity;
};
``` | I understand velocity is a vector (v1, v2, v3), also position is a point in 3d space (p1, p2, p3).
Now in a trajectory, a point can have both velocity and position, velocity and position are both needed. For one thing you can not use virtual inheritance.
I think composition makes more sense.
```
class Trajectory
{
public:
Position p;
Velocity v;
};
``` |
479,618 | I am using WCF to a soap endpoint using security mode "TransportWithMessageCredential".
The WCF client/server uses SCT (Security Context Token) to maintain a secure connection, and it is working as intended in the general case.
However, after a period of inactivity, the SCT will be expired and the next method call will cause a MessageSecurityException:
>
> An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail
>
>
>
Inner exception:
>
> The message could not be processed. This is most likely because the action '<http://tempuri.org/IMyService/MyMethod>' is incorrect or because the message contains an invalid or expired security context token or because there is a mismatch between bindings. The security context token would be invalid if the service aborted the channel due to inactivity. To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint's binding.
>
>
>
On subsequent calls, I renew the connection when I see that CommunicationState is Faulted. But I cannot find a way to preemptively check whether the SCT has expired before making my method call. | 2009/01/26 | [
"https://Stackoverflow.com/questions/479618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42272/"
] | You could resolve your issues by using delegates. This will allow to safely invoke the action and, if fails, catch the exception, construct a new service instance and perform the action again.
```
using System;
using System.ServiceModel;
using System.ServiceModel.Security;
public static class Service
{
private static IService _service;
public static void Invoke(Action<IService> action)
{
try
{
action(_service);
}
catch (MessageSecurityException)
{
if (_service.State != CommunicationState.Faulted)
{
throw;
}
_service.Abort();
_service = CreateFreshInstance();
action(_service);
}
}
}
```
You could then call your helper class like `Service.Invoke(s => s.Method());` to invoke the IService.Method(). | You might be able to use the decorater pattern to handle exceptions with WCF proxies. If this path is open to you, you can consider something like this set-up which will handle the proxy faulting and re-initialise it for callers. Subsequent exceptions will be thrown up to the caller.
```
//Proxy implements this
interface IMyService
{
void MyMethod();
}
//Decorator 1
public class MyServiceProxyRetryingDecorator : IMyService
{
//This is the real proxy that might be faulted
private realProxy = new RealProxy();
public void MyMethod()
{
ReEstablishProxyIfNecessary();
//now just pass the call to the proxy, if it errors again,
//do more handling or let the exception bubble up
realProxy.MyMethod();
}
private void ReEstablishProxyIfNecessary()
{
if(realProxy.CommunicationState == CommunicationState.Faulted)
{
realProxy.Abort();
realProxy = new RealProxy();
}
}
}
```
An different version of the decorator could have the decorator handling your MessageSecurityException, and re-initialising the real proxy when it is caught:
```
//Decorator 2
public class MyServiceProxyExceptionHandlingDecorator : IMyService
{
//This is the real proxy that might be faulted
private realProxy = new RealProxy();
public void MyMethod()
{
try {realProxy.MyMethod(); }
catch (ExceptionYouAreInterestedIn ex)
{
ReEstablishProxyIfNecessary();
realProxy.MyMethod(); //do it again
}
}
private void ReEstablishProxyIfNecessary()
{
if(realProxy.CommunicationState == CommunicationState.Faulted)
{
realProxy.Abort();
realProxy = new RealProxy();
}
}
}
``` |
71,121,323 | This is a old question, I know
[Yocto: why is a package included?](https://stackoverflow.com/questions/26238210/yocto-why-is-a-package-included)
[Why is package included in Yocto rootfs?](https://stackoverflow.com/questions/67785619/why-is-package-included-in-yocto-rootfs)
but there is not satisfactory answer.
I get **valgrind** inside my yocto custom image (sustitute valgrind with whatever package name) and I do not why.
Valgrin's recipe **RDEPENDS** variable show what packages will be installed in the image for valgrind runs.
Is there any way to know the reverse function? that is, what recipe has in his RDEPENDS **valgrind**?
**bitbake -g valgrind** or find **valgrind** in recipes files do not help. | 2022/02/15 | [
"https://Stackoverflow.com/questions/71121323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7793992/"
] | One way you can do this is like so using `CustomPainter`.
```
class SampleExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const Scaffold(
backgroundColor: Colors.red,
body: Align(
alignment: Alignment.bottomCenter,
child: CustomPaint(
painter: MyCustomPainter(),
child: SizedBox(
width: double.infinity,
height: 250,
child: Center(child: Text('Cool!')),
),
),
),
);
}
}
class MyCustomPainter extends CustomPainter {
const MyCustomPainter();
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.white
..style = PaintingStyle.fill;
final path = Path()
..moveTo(0, 0)
..quadraticBezierTo(size.width / 2, size.height / 4, size.width, 0)
..lineTo(size.width, size.height)
..lineTo(0, size.height)
..close();
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
```
[](https://i.stack.imgur.com/rl7jY.png) | ```
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ClipPath(
clipper: CurveClipper(),
child: Container(
color: Colors.lightGreen,
height: 250.0,
child: Center(
child: Padding(
padding: EdgeInsets.only(bottom: 50),
child: Text(
"Curved View",
style: TextStyle(
fontSize: 25,
color: Colors.white,
),
),
)),
),
),
),
);
}
}
class CurveClipper extends CustomClipper<Path> {
@override
Path getClip(Size size) {
int curveHeight = 40;
Offset controlPoint = Offset(size.width / 2, size.height + curveHeight);
Offset endPoint = Offset(size.width, size.height - curveHeight);
Path path = Path()
..lineTo(0, size.height - curveHeight)
..quadraticBezierTo(controlPoint.dx, controlPoint.dy, endPoint.dx, endPoint.dy)
..lineTo(size.width, 0)
..close();
return path;
}
@override
bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}
``` |
6,451,441 | I need to get the RGB value of a color given it's name in C#. I am trying to use the predefined KnownColors enum, but can't figure out how to get the value.
Any help?
Thank you. | 2011/06/23 | [
"https://Stackoverflow.com/questions/6451441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/331785/"
] | Use [`FromKnownColor`](http://msdn.microsoft.com/en-us/library/system.drawing.color.fromknowncolor.aspx):
```
Color blue = Color.FromKnownColor(KnownColor.Blue);
```
Then `blue.R`, `blue.G` and `blue.B` for the RGB values.
---
Or, if you just want the `int` value for the RGB color, you can do:
```
int blueRgb = Color.FromKnownColor(KnownColor.Blue).ToArgb();
``` | ```
Color clr = FromKnownColor(System.Drawing.KnownColor.Blue);
string.Format("R:{0}, G:{1}, B:{2}" clr.R, clr.G, clr.B);
```
Check this [Out](https://stackoverflow.com/questions/225953/c-color-constant-r-g-b-values) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.