INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Why do lone pairs of electrons have a higher repulsive force?
I was just wondering why lone pairs of electrons are more repulsive than bonded pairs of electrons.
I have read that lone pairs have orbitals which are shorter and more round, compared to bonded pairs. I assume, therefore, that this difference in repulsive force could be due to the increased surface area that these orbitals provide, which would cause more repulsive force to be directed towards electrons.
Of course this is just a presumption that I made, which is probably incorrect. | Bonding pairs are stabilized between two atoms. Since there's no atom on the other end of a lone pair, it spreads out more than would be if it were in a bond. Lone pairs therefore repel more because the charge density is spread out more, that is, it's bigger.
> I have read that lone pairs have orbitals which are shorter and more round
This is technically true in the sense that you'd want to have higher $s$ character in a lone pair orbital. But you're comparing possible ways to hybridize orbitals for lone pairs, as opposed to comparing lone pair atomic orbitals with bonding orbitals. | stackexchange-chemistry | {
"answer_score": 2,
"question_score": 3,
"tags": "electrons, orbitals, intermolecular forces"
} |
SSIS Unknow delimiter Encountered
I am currently working on a ssis project i have a data like this
col1þcol2þcol3þcol4
i have followed steps from here How to read a flatfile with lowercase thorn as the delimiter
but the data looks like this ?
`col1þcol2þcol3þcol4` on loading in ssis Flat file connection manager !
What should be delimiter in this case ? | `þ` is a thorn delimiter
then you need to change the xml code (goto view-->code)
`DTS:ColumnDelimiter="_x002C_"`
or as said by @jayvee paste `þ` or try pasting `þ` | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sql server, ssis"
} |
Why $\{A_n \quad a.a.\}:=\bigcup_{n=1}^\infty \bigcap_{k=n}^\infty A_k$ is not defined as $\lim_{n\rightarrow\infty} \bigcap_{k=n}^\infty A_k$?
Given a probability tripple $(\Omega, F, P)$ and infinite many events $A_1, A_2, \dots, \in F$, a new event "almost always" in $F$ is normally defined as:
$$\\{A_n \quad a.a.\\}:=\bigcup_{n=1}^\infty \bigcap_{k=n}^\infty A_k$$
I'm wondering, why it is not defined as $$\\{A_n \quad a.a.\\}:=\lim_{n\rightarrow\infty} \bigcap_{k=n}^\infty A_k$$ ? The two definitions look equivalent to me and the latter is easier to understand. | The first definition is easiest to understand in my opinion. It describes all those sets for which only finitely many $A_n$ are not in $F$.
> Regarding your suggestion the set-theoretic limit is defined as follows. Let the _limit infinum_ and _limit supremum_ be defined as \begin{equation*} \liminf_{n\rightarrow \infty}A_n = \bigcup_{n \geq 1} \bigcap_{j \geq n} A_j \qquad \limsup_{n\rightarrow \infty}A_n = \bigcap_{n \geq 1} \bigcup_{j \geq n} A_j. \end{equation*} If the two coincide the set theoretic limit exists and is equal to the resulting set.
You can see that the first definition for "almost always in $F$" is equal to $\liminf_{n\rightarrow \infty}A_n$. As pointed out in the comments $B_n = \bigcap_{j \geq n} A_j$ is an increasing sequence and thus $$\lim_{n\rightarrow \infty} B_n = \liminf_{n\rightarrow \infty}B_n = \bigcup_{n \geq 1} \bigcap_{j \geq n} B_j = \bigcup_{n \geq 1} B_n = \bigcup_{n \geq 1} \bigcap_{j \geq n} A_j= \liminf_{n\rightarrow \infty}A_n.$$ | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "probability"
} |
Returning separate txt files from loop in R
I want to return the results of each iteration in a loop to be written in a separate text file, but for some reason it does not seem to work. My code is:
for (i in length(traject)){
player <-subset(traject[[i]],subset=(dt==1),)
test<-player
write.table(test, file=paste(i, "test.txt", sep=" "))
head(test)
}
Which only return the last iteration, what do i do wrong to produce the results of all iterations in separate text files?
Extra info: The loop is for each separate player (with different ID's) to gain data via as.ltraj() from the adehabitatLT package.
_(i know there are similar questions on this forum but none could help me in solving this problem)_ | Maybe you should add `1:length(traject)` in your `for` loop as in:
for (i in 1:length(traject)){ do something }
Your loop is only returning one iteretion (the last one) because your index is just `length(traject)` instead you should use `1:length(traject)` for the index `i` to move from the first element all the way to the last one, you can also replace `1:length(traject)` by `seq_len(length(traject))` | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "r, for loop"
} |
lower bound for the condition number
I have shown that if we have an invertible matrix $A \in \mathcal{M}_{N}(\mathbb{R})$ and $C \in \mathcal{M}_{N}(\mathbb{R})$ such that $A+C$ is singular then $cond(A) \geq \frac{\mid \mid A \mid \mid }{\mid \mid C \mid \mid }.$
Now given this matrix $ \left( \begin{array}{ccc} 1 & -1 & 1 \\\ -1 & \alpha & \alpha \\\ 1 & \alpha & \alpha \end{array} \right)$ I want to use this result to find a lower bound $l_{\alpha}$ for $cond_{\infty} A$ such that $ \underset{\alpha \rightarrow 0} {\lim} l_{\alpha} = + \infty .$ Any hint? | Take $C=\begin{pmatrix}0&0&0\\\0&-\alpha&-\alpha\\\0&-\alpha&-\alpha\end{pmatrix}$. If $\alpha$ is small, then $cond_{\infty}(A)\geq l_{\alpha}=\dfrac{3}{2|\alpha|}$. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "linear algebra, matrices, numerical linear algebra, condition number"
} |
Best way to support functionality for previous iOS versions and deprecated methods
stretchableImageWithLeftCapWidth:topCapHeight: is method that used for resize image (iOS lower than 5.0), but in iOS 5 that method is deprecated and iOS 5 have the new one resizableImageWithCapInsets:
What the best way to support resize images in iOS lower than 5 and greeter than 5? First thing that I know is to use responseToSelector method. But perhaps somebody know an other examples. | It is generally pretty simple to support versions, the only pitfall to avoid is using conditional building to decide what features to support as that would require you to use a specific binary for each version.
I would use something like this:
NSString* featureVersion = @"5.0";
NSString* systemVersion = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
{
[object someIOS5SpecificMethod];
}
else
{
[object alternateMethod];
}
To use version specific classes you could always use something similar to:
Class class = NSClassFromString(@"iOS5OnlyClass");
if (class)
{
id object = [[class alloc] init];
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "iphone, ios, ipad, uiimage, image resizing"
} |
Why does a shebang script run as init= have an euid of 0 when run from an initrd, but not otherwise?
I am trying to create my own PID 1 init script, to be called from the boot cmdline with init=/myscript. How can I make it work on a real filesystem, with any kernel?
When it runs in an initrd, it works fine and can mount things, etc. - but when I use it on my filesystem without an initrd, it fails to mount things, because:
mount: only root can do that (effective UID is 1000)
When I strace any command that fails, it inevitably issues geteuid32() and that returns 1000. Why? How can I run as euid 0? | There's no special treatment for `init` on `initrd`, so there must be some other issue.
If run as `root`, the `euid` will match the owner of the binary if the `setuid` bit is set.
Check the ownership on `/bin/mount`. | stackexchange-unix | {
"answer_score": 0,
"question_score": 1,
"tags": "linux, kernel, initrd, shebang"
} |
PostgreSQL query: obtain concise string of numbers
Obtain a concise string of the numbers, for example, given 1,2,3,6,7,8,9,12,14, we expect 1-3,6-9,12,14.
Here is the Table:
create table tt8 (c1 numeric);
insert into tt8 values
(1),(2),(3),(6),(7),(8),(9),(12),(14);
Use Table tt8, Here is what the result should look like:
numbers
---------------
1-3,6-9,12,14
Here is what I have so far, but it's giving me type error. I don't think this is the correct way.
select c1,
case
when c1 = 1|2|3 then '1-3'
when c1 = 6|7|8|9 then '6-9'
else c1
end
from tt8; | You can use a gaps-and-islands approach and then aggregation. The following gets the groups:
select min(c1) || (case when count(*) = 1 then '' else '-' || max(c1) end)
from (select tt8.*, row_number() over (order by c1) as seqnum
from tt8
) t
group by (c1 - seqnum);
You can then put them into a single string:
select string_agg(val, ',' order by min_c1)
from (select min(c1) || (case when count(*) = 1 then '' else '-' || max(c1) end) as val, min(c1) as min_c1
from (select tt8.*, row_number() over (order by c1) as seqnum
from tt8
) t
group by (c1 - seqnum)
) t;
Here is a db<>fiddle. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, database, postgresql"
} |
Select element in matrix with index from other matrix
I am trying to select an element from matrix z with an index from matrix y. When indexing it like this `z[1,y[1,1]]` it gives another value than when indexing it like this `z[1,15]` (with `y[1,1] = 15`). How come?
> z[1,y[1,1]]
[1] 15
> y[1,1]
[1] 15
> z[1,15]
6/09/2021
1: 2 | It may be due to rounding differences. This can happen when you stored a vlue into `y[1,1]` which was a result from a calculation.
Let me give you an example when this can happen.
mat <- matrix(1:10, ncol = 2)
print(mat)
# [,1] [,2]
# [1,] "a" "f"
# [2,] "b" "g"
# [3,] "c" "h"
# [4,] "d" "i"
# [5,] "e" "j"
ind <- exp(4) / 54.598152 * 2
print(ind)
# [1] 2
print(mat[1, ind]) # Extracts the value from the first column.
# [1] "a"
print(mat[1, round(ind)]) # Extracts the value from the second column.
# [1] "f"
Therefore, try using `z[1, round(y[1,1])]` to check if the problem persists. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "r, indexing"
} |
Upload the app to AppStore which contains firebase
Can I publish the app which contains firebase to AppStore ? Does google approve of this ? | Yes you can upload your app with firebase to Apple store.
There is nothing specific in the Firebase Database that makes it different between the app in development, testing or live on the app store.
you can check similar question at here Submitting an app to the App Store that uses Firebase | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "ios"
} |
What is the jQuery ajax equivalent to this html-form submit?
If have a html form like
<form method="POST" action="
<input type="text" name="data" id="data" />
<input type="submit" />
</form>
I want to make a ajax-request with jQuery, but I don't want to use an invisible form to submit this. But somehow I don't get it to work. My try was
$.ajax({
type: "POST",
url: "
data: d,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
were `d`contains a JSON object which I would just paste in the above form field as plaintext. The success function gets executed, but I don't get the answer from the server (which means that something must go wrong :-) | Are you POSTing on the same domain? Ajax doesn't work cross-domain. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "jquery, ajax, json"
} |
Passing an array value into the jQuery selector method?
At the moment in my JS I statically define which input ID's I want to associate my datepicker script with.
Like so:
$('datepicker1').glDatePicker();
However to make this dynamic I have refactored this into a for loop so that for multiple fields that need a datepicker I can call them in that loop.
dateArray[y] = "datePicker" + i;
//out of loop scope
for (i = 0; i < dateArray.length; i++)
{
$(dateArray[i]).glDatePicker();
}
It does not seem to work , I have checked that there are values in the array by printing the values to the log.
Is this a limitation of jQuery?
Thanks | You need to set it as an id with `"#"`
$("#" + dateArray[i]).glDatePicker(); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "jquery, jquery selectors"
} |
Print words in the index - Lucene
I'm very new to Lucene and I'm using Lucene 4.10.4. For some clarifications, I'm trying to print all the words which lucene read from the index during search time. I'm trying to understand, based on the search string what all the words in the index are skipped from comparing by Lucene. I tried printing the words using print statements in some lucene class. But it didn't work. Where can I use the print statement? | Something like this, should work for you. This code, opens **Lucene** index and iterating through all fields and lists all terms. You could easily skip not needed fields here
IndexReader reader = DirectoryReader.open(dir);
final Fields fields = MultiFields.getFields(reader);
final Iterator<String> iterator = fields.iterator();
while(iterator.hasNext()) {
final String field = iterator.next();
final Terms terms = MultiFields.getTerms(reader, field);
final TermsEnum it = terms.iterator(null);
BytesRef term = it.next();
while (term != null) {
System.out.println(term.utf8ToString());
term = it.next();
}
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "java, lucene"
} |
Approximating a random variable versus approximating probability statements about a random variable?
After formally stating the central limit theorem my statistics textbook says this:
> Interpretation: Probability statements about the sample mean $\overline{X}_n$ can be approximated using a Normal distribution. It's the probability statements that we are approximating, not the random variable itself.
What distinction are they trying to make here? What would it mean to approximate a random variable other than to approximate probability statements about it? | Under certain conditions, the probability $P(\bar{X}_n \in [-1, 1])$ (for example), which is a non-random number, can be approximated by $P(Y \in [-1, 1])$ for some normal random variable $Y$ with appropriate mean and variance, using the central limit theorem. To emphasize, you are approximating the _probability_ $P(\bar{X}_n \in [-1, 1])$, and not the random variable $\bar{X}_n$ itself: you are not saying something is close to $\bar{X}_n$. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "statistics, random variables, approximation, central limit theorem"
} |
Bash arithmetic expression (( in compound statement [[ returns true?
Simple arithmetic expression enclosed in '((' evaluates to true when inside compound conditional expression '[['
HAVE_SRC=1
[[ (( $HAVE_SRC == 1 )) && -d $( pwd ) ]]
echo $? # returns 0 => true
HAVE_SRC=0
[[ (( $HAVE_SRC == 1 )) && -d $( pwd ) ]]
echo $? # returns 1 => false
HAVE_SRC=1
[[ (( $HAVE_SRC )) && -d $( pwd ) ]]
echo $? # returns 0 => true
**PROBLEM:**
HAVE_SRC=0
[[ (( $HAVE_SRC )) && -d $( pwd ) ]]
echo $? # returns 0 => true ???? | Do not use `(( ... ))` inside of `[[ ... ]]`:
(( HAVE_SRC == 1 )) && [[ -d $pwd ]]
To see how bash interprets the expressions you gave, try running them with
set -xv | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "linux, bash, shell, math, expression"
} |
What is the range of $x+\frac{1}{x}$ if $-2\leq x \leq 2$
What is the range of $x+\frac{1}{x}$ if $-2\leq x \leq 2$?
My try:
$-2\leq x \leq 2$
$\Rightarrow \frac{-1}{2}\leq x \leq \frac{1}{2}$
$\Rightarrow \frac{-5}{2}\leq x+\frac{1}{x} \leq \frac{5}{2}$
Am i correct or wrong?If not,please help me solve this. | For $x=0$, the expression makes no sense. Furthermore, the function $f(x)=x+\frac1x$ is odd, so it suffices to consider the interval $(0,2]$.
The derivative $$f'(x)=1-\frac1{x^2}$$ is negative at $(0,1)$ and positive at $(1,2]$. At $x=1$ there is a minimum and $f(1)=2$, and $$\lim_{x\to0^+}f(x)=\infty$$ therefore, the range for $f(x)$ at $(0,2]$ is $[2,\infty)$.
Can you finish? Remember that $f$ is odd.
It would be good also to notice that $f$ reaches every intermediate value, due to its continuity. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "inequality"
} |
In a dict of dicts, how do you emulate Perl's auto-vivification behavior?
Both Google and the online docs are not delivering much insight on my query, so I thought I would ask the community here.
In Perl, you can easily setup a hash-of-a-hash-of-a-hash and test the final key like so:
my $hash = {};
$hash{"element1"}{"sub1"}{"subsub1"} = "value1";
if (exists($hash{"element1"}{"sub1"}{"subsub1"})) {
print "found value\n";
}
What's the 'best-practice' equivalent in Python? | The closest equivalent is probably something like the following:
import collections
def hasher():
return collections.defaultdict(hasher)
hash = hasher()
hash['element1']['sub1']['subsub1'] = 'value1'
if 'subsub1' in hash['element1']['sub1']:
print 'found value' | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 13,
"tags": "python, dictionary, autovivification"
} |
format specifier for long double (I want to truncate the 0's after decimal)
I have a 15-digit floating-point number and I need to truncate the trailing zeros after the decimal point. Is there a format specifier for that? | `%Lg` is probably what you want: see < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "iphone, objective c, c, xcode"
} |
iBeacon detection by Mobile Phone Browser
Does anyone know of a script available to access the Blue tooth driver in a mobile device (Apple and Android) to see if an iBeacon is in range?
I am building an Web Page that requires location sensing capabilities for security and this would be ideal.
Thanks in advance. | Sorry, as of November 2016 there are no bindings for major mobile browsers to access Bluetooth LE scan results in general, or more specifically beacon detections. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "html, ibeacon"
} |
How to update values from a table using a NTILE function?
**Abstract:** I am trying to rank these stocks factors by top quintile and bottom quintile to build a long/short portfolio.
Table:
 OVER (ORDER BY [2006-12-30] DESC)
FROM MOMENTUM_Quintile
Error message:
> Msg 4108, Level 15, State 1, Line 7
> Windowed functions can only appear in the SELECT or ORDER BY clauses. | The error is clear,reason why you can't do this,has to do with Logical query processing .you can try below
With cte
as(
select *, NTILE(5) OVER (order by [2006-12-30] desc) as ntile
from
MOMENTUM_Quintile
)
update cte
set [2006-12-30]=ntile | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "sql server, tsql"
} |
Can there be an object (e.g. a list) instead of a test expression in python 'elif'?
def lines(file): # a text file
for line in file:yield line
yield "\n"
def blocks(file):
block=[]
for line in lines(file):
if not line.isspace():
block.append(line)
elif block: #a list in elif test expression
yield ''.join(block).strip() | So long as the list isn't empty then yes you can use a list to be evaluated as a `True` bool in and if/elif/else statement. Empty lists will be `False`, lists with at least 1 item will be `True`
You can always just try your own code out to see for yourself! | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "python, if statement"
} |
How can I made an AddressBook synchronized with my Iphone addressbook?
I have to made an app with an AddressBook, different by the internal iphone AddressBook, but I need to take informations from it (and I can do that), and I need to know (if exists) the internal AdressBook last modify date, so i could sync my app's addressbook with the internal one only if it occours, HOW I CAN DO THAT?? THANK YOU AND SORRY FOR MY BAD ENGLISH! | Are you storing Contacts to your app locally ? if Not then You don't have to Sync.
ABAddressBook is centralized DB of contacts. so every time your app open you are using ABAddressBook to load the contacts it should get the all latest contacts. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "iphone, xcode, synchronization, addressbook"
} |
Git command to get SVN style diff; modified file list between revisions
I used the command `"git diff --name-only"` and got output like below
FilePath/FilePath/FileName.ext
FilePath/FilePath1/FileName1.ext
I need SVN style output like
M FilePath/FilePath/FileName.ext
A FilePath/FilePath1/FileName1.ext
How to achive this? | Try the "--name-status" option instead of "--name-only":
git diff --name-status
Example output:
git diff --name-status HEAD~1 HEAD
M .gitignore
A src/File1.java
A src/File2.java
M src/File3.java | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "gitlab, git"
} |
Search MySql database for a HTML link using PHP
I have mysql table that contatins item_id and link columns the link column contains html tags and the actual link. now I want to search the database for a link that doesn't contain html tags what is the best way to do this in php? | The easy answer depends on assumptions you can make based on what you know about the data.
If these links were inserted programmatically, and you trust your own code to create well-formed links, you can eliminate anything that includes the link closure.
SELECT mytable.item_id FROM mytable WHERE mytable.link NOT LIKE '%</a>%' | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql, html"
} |
svn or mercurial version control of word documents
As far as I know, Microsoft went to some sort of xml-based representation in their most recent version of office. If that's really true, then I would assume that version control would work, although you would obviously have to resolve any embedded changes with the old
<<<<<<
======
>>>>>>
marks in them before loading word.
This other question mentions the issue, but it seems to be taken as a foregone conclusion that version control simply won't work in Word, and I want to know why?
Is version control (ie. Subversion) applicable in document tracking? | There's the zipdoc extension for Mercurial, which seems to handle compressed files like XML-based Word documents by storing them uncompressed internally in order to get meaningful deltas and in order to merge them in a meaningful way. I did not test it, but it sounds like the thing you're looking for. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 4,
"tags": "svn, mercurial, ms word"
} |
Escaping multiple different characters in a String
I want to escape different characters (`#, $, %, &, \, ^, _, {, }, ~`) in a given Java String with a backslash (`#` becomes `\#`, `$` becomes `\$` and so on).
Is it possible to archieve this without calling the `String#replace` or `String#replaceAll` method multiple times on the string? | You can use the following regular expression
String escaped = s.replaceAll("[" + Pattern.quote("#$%&\\^_{}~") + "]",
Matcher.quoteReplacement("\\")+"$0") | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "java"
} |
php hash form string to integer
Does PHP have a built in function for doing string to integer hashes, something that's difficult to reverse?
Now, I know I can probably get away with doing an md5, and treating a substring of it as a radix 16 number, but I'm looking for something built in.
Thanks. | I think the best bet would chose a standard hash [either `md5()` or `sha1()`] to obtain a hash of your string, and then to get an integer hash, to a `base_convert($hash, 16, 10)` and that should convert your hash into a integer hash.
Hope I am understanding your issue correctly. | stackexchange-stackoverflow | {
"answer_score": 35,
"question_score": 15,
"tags": "php, hash, integer"
} |
Kaggle: TrackML Particle Tracking Challenge
I'm new to ML and Kaggle. I was going through the solution of a Kaggle Challenge.
Challenge: <
Solution: <
While going through the code, I noticed that the author has used only train_1 file (not train_2, 3, …).
I know there is some strategy involved behind using only the train_1 file. Can someone, please, explain why is it so? Also, what are the use of blacklist_training.zip, train_sample.zip, and detectors.zip files? | I'm one of the organiser of the challenge. train_1 2 3 .. files are all equivalent. Outrunner has probably seen there was no improvement using more data.
**train_sample.zip** is a small dataset equivalent to train_1 2 3... provided for convenience.
**blacklist_training.zip** is a list of particles to be ignored due to a small bug in the simulator (not very important).
**detectors.zip** is the list of the geometrical surfaces where the x y z measurements are made.
David | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "machine learning, physics, kaggle"
} |
Convert one level object to nested objects in javascript
So, given this structure of object:
{
property1: 'value1',
property2.property3: 'value2',
property2.property7: 'value4',
property4.property5.property6: 'value3',
}
Need to be converted to this look:
{
property1: 'value1',
property2: {
property3: 'value2',
property7: 'value4'
},
property4: {
property5: {
property6: 'value3'
}
}
}
Just simple example. I'd like to see most optimized and beautiful solution. Obviously it should be function that takes first object as input and outputs second. Thank you for your time in advance. | A rough implementation can be
function convert(obj) {
var res = {}, i, j, splits, ref, key;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
splits = i.split('.');
ref = res;
for (j = 0; j < splits.length; j++) {
key = splits[j];
if (j == splits.length - 1) {
ref[key] = obj[i];
} else {
ref = ref[key] = ref[key] || {};
}
}
};
}
return res;
}
Demo: Fiddle | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -6,
"tags": "javascript"
} |
Can I use thymeleaf syntax inside of javascript code?
Here is the part of the code that I try to take out to .js file
$(document).ready(function () {
$("#buttonCancel").on("click", function () {
window.location = "[[@{/users}]]";
});
});
and link to this file from .html right before close body tag:
<script type="text/javascript" th:src="@{/js/userForm.js?v=1}"></script>
If I click "Cancel" I have an error 400. Yes, I can use "window.location = "/myweb/users";" and it works well. But I am curious if there any way to use th-syntax in javascript file? | As alternative, you could create a hidden link in your HTML, and then use it in your script:
HTML:
<a id="cancelAction" style="display:hidden" th:href="@{/users}"></a>
JavaScript:
$(document).ready(function () {
$("#buttonCancel").on("click", function () {
$("#cancelAction").click();
});
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, html, thymeleaf"
} |
Where can I go and watch Flamenco shows in Istanbul?
Does Istanbul have cafés, bars or theatres where one can go and watch Flamenco shows?
I know there are places where they teach Flamenco but I just want to witness the performance. | You are in luck. There exists the Istanbul Flamenco Association (website in Turkish only) which can probably provide you with all the information you need. Below are their contact details:
Flamenko İstanbul Derneği
Firuzağa Mahallesi Bostanbaşı Caddesi Külünkoğlu Apartmanı no:5 /1
( Fransız Sokağı Alt Girişi )
Taksim
E-Posta: [email protected]
GSM : 0505 601 71 28 – 0535 233 47 70
They regularly organise festivals and events. For example, the last Flamenco festival took place in February 2015. They also organised a workshop in the same month. It is therefore safe to assume that they are currently active. Indeed their facebook page also shows recent activity. The website also has a page dedicated to what they call Group Shows which says you can contact the association for more information regarding
> Various events, exhibitions, openings, festivals, concerts, cocktails, dinners, exhibitions and special day of your lives | stackexchange-travel | {
"answer_score": 2,
"question_score": 5,
"tags": "culture, istanbul"
} |
How to cancel a restart in Mac OS X 10.6
When I hit restart, after a second or two, everything closes and the machine restarts. But sometimes, within that second I realize that I really didn't want restart just then. How can I stop the machine from restarting at that time?
The best way I can figure out is to cancel a save request if something needs saving, but that isn't always the case. | if you're really quick you could open a terminal window and type
sudo killall shutdown
that might work. Otherwise, quickly open an application that always asks if you really want to quit. You could use applescript to make such an application:
on quit
display dialog "Really shut down?" buttons {"No", "Yes"} default button "no"
if the button returned of the result is "Yes" then
continue quit
end if
-- If I don't continue the quit, the app will keep running.
end quit
type that into the applescript editor and save it as an application, then put it somewhere handy.
NB. Both of these methods may not work. I'm too lazy to find out if they do, because it might involve having to reboot several times. | stackexchange-superuser | {
"answer_score": 9,
"question_score": 5,
"tags": "macos, osx snow leopard, reboot"
} |
Difference between spanning set and a basis
Can anybody please shed some light on the difference between a spanning set and a basis? | A _basis_ is a spanning set that is also _linearly independent_.
For example, consider the vector space $\mathbb{P}$ of all linear polynomials over $\mathbb{R}$, of the form $$ \mathbb{P} = \\{a+bx|a,b\in \mathbb{R}\\}. $$ Let $\vec{u} = 1, \vec{v} = x, \vec{w} = 1+x$ and let $S = \left\\{\vec{u},\vec{v},\vec{w}\right\\}$.
Note that $S$ spans $\mathbb{P}$, but it not linearly independent, hence $S$ is **not** a basis for $\mathbb{P}$. To get a basis, take any 2 elements of $S$. | stackexchange-math | {
"answer_score": 2,
"question_score": -1,
"tags": "linear algebra, vector spaces"
} |
input diccionario
Alguien sabe como agregar un diccionario completo en un input, literalmente como:
dic = input("{"y":99,"k":67,"o":99}")
Algo así, que luego se pueda llamar de la siguiente forma:
print(dic["y"])
-->return "99"
Si lo agrego tal cual lo pongo acá, no funciona, porque me toma el input como una lista, entonces claro, si más adelante llamo un key, para obtener su código, pues no funciona.
Gracias. | Buen día,
Para lograrlo puedes utilizar el módulo `json`
import json
dic = input('Ingresa un diccionario: ')
res = json.loads(dic)
Y ya podemos utilizar el diccionario de forma normal, por ejemplo, si agregaramos la línea
print(res['a'])
E ingresaramos el siguiente `string`: `{"a": [1,2,3,4], "b": [5,6,7,8]}`
Esto nos devolvería
[1, 2, 3, 4]
Es decir, con el módulo `json` puedes ingresar cualquier `string` con sintaxis de diccionario y puedes utilizar sus llaves y valores de la misma forma que utilizas un diccionario.
**Nota:** Al ingresar el `string` es necesario utilizar comillas dobles `"` para los nombres de las llaves. | stackexchange-es_stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "python, json"
} |
System.Net.Mail.SmtpException: Cannot get IIS pickup directory
Fellas,
Getting the "Cannot get IIS pickup directory" exception with my app. I have my directory created and specified in the config as follows:
<system.net>
<mailSettings>
<smtp deliveryMethod="PickupDirectoryFromIis" from="[email protected]">
<specifiedPickupDirectory pickupDirectoryLocation="C:\inetpub\email\mysite"/>
</smtp>
</mailSettings>
</system.net>
Trying to have the emails placed locally in a directory so I can see them.
Any ideas why it could be throwing that exception?
FWIW, this is IIS7 + Windows 7 and an MVC2 app (C#).
Also, went ahead and gave permissions to the IIS_IUSRS group to that directory. | All,
Seems like I was using the wrong smtp deliveryMethod. I got the PickupDirectoryFromIis and SpecifiedPickup deliveryMethod's mixed up, and hence was using the wrong settings for it. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "iis 7, system.net.mail"
} |
How to open local help files in VS 2012 Professional?
I installed help documentation for C++ on my local disk within Visual Studio 2012 Pro. But whenever I press F1 the MSDN homepage will open in my browser instead of the local help documentation.
How can I open the local documentation? | In Visual Studio: Help Menu -> Set Help Preference -> Launch in Help Viewer | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "visual studio 2012"
} |
C++ x = P > Q equivalent in C#
I am trying to convert a C++ program to C#. I came across a line of statement as below.
int X;
int P = 10;
int Q = 5;
X = P < Q;
It make sense to me if X is a bool value. However X is an integer. I am wondering what the output of X would be. It might be a very basic syntax in C++. Sorry for my ignorance. I am after an equivalent statement in C#. Any advice is appreciated.
Thanks | In C# the assignment would not be permitted, because (as you guessed) the expression `P < Q` would be of the type `bool`. This C# code would be roughly equivalent:
int X;
int P = 10;
int Q = 5;
X = (P < Q) ? 1 : 0; | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "c#"
} |
What is the Dragonfire scorestreak and how do I use it?
I haven't had the game long and have only been playing online multiplayer so far. I just earned the Dragonfire scorestreak but I dont know how to use it. Everytime I tried with the conventional method of pressing right on the d-pad, it just kept saying that I couldn't use that here. I tried it inside, outside, against the floor, against a wall, against a vehicle... nothing!
Anybody know how I am supposed to use it? | It looks like it is glitchy.
<
< | stackexchange-gaming | {
"answer_score": 1,
"question_score": 2,
"tags": "call of duty black ops 2"
} |
SimpleCov: Not run every time, just with rake task
Is there a possibility to run simplecov coverage-tool for rails just over an rake task and not every time, when running the tests? | You can sort of work around this using an environment variable:
SimpleCov.start if ENV["COVERAGE"]
And then, running rake test / rspec / cucumber with
$ COVERAGE=true rake test | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 7,
"tags": "ruby on rails, rubygems"
} |
Regular Expression Check To See If String Contains All The Same Numbers
I'm new to regular expressions and for a project I'm working on I was required to validate a field to see if the 10 digit number entered contained all the same numbers.
I found the following solution:
([1-9])\\1{9}
source: <
I have tried to Google it, but nothing that explains what the expression is doing. I was wondering if someone could explain how this expression works. | It works like this:
([1-9]) // Capture any number 1-9 and store it as the first "capture"
\1 // Substitute the first "capture" as raw text into the regex
{9} // Match that raw text another 9 times (i.e. 10 in total)
Be sure that `0000000000` shouldn't match your expression since this isn't matched by `[1-9]` | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "regex, expression"
} |
How do I find more infos about an auto discoverd printer in local network?
My printing dialogue shows some printers I don't knwo about. One is called "duerqxesz5090", one "print" and the last one "prt0". prt0 has "Hacked by Swan" as location, so I want to know what device this is. (Screenshot)
But I don't know how this printer is discovered and how I find out more about it. Is this done via SSDP?
I am using lubuntu 17.04 | The `avahi-discover` tool gave me the missing information. | stackexchange-serverfault | {
"answer_score": 2,
"question_score": 2,
"tags": "network printer, ssdp"
} |
Stop Gist MarkDown characters from interfering with one another?
I am using Gist to publish a page in MarkDown about JavaScript operators. Within my document I am building a table, however I want to include characters in my table that interfere with the pages MarkDown syntax.
This is a portion of my table is MarkDown
| Syntax | Type |
| --- |: --- :|
| a | b | Bitwise OR |
| a && b | Logical AND |
| a || b | Logical OR |
As you can see, because the table is including the character '|' within its contents, MarkDown thinks this is part of the table and formats it incorrectly. How can I avoid this formatting issue?
I have tempted to wrap the content in HTML comments tags `<!-- -->` and `<p></p>` tags both to no avail. | You can use the backslash character to escape the pipes within the cell's text.
| Syntax | Type |
|-------------|:--------------:|
| a \| b | Bitwise OR |
| a && b | Logical AND |
| a \|\| b | Logical OR | | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, github, markdown, gist"
} |
Octet binary format in shell script
i cut the ip add ect: 10.0.0.0/4 into octet then when i change the octet to binary, it only appear like 1010 not 00001010, how can i make the output with octet format like 00001010. I already try
#!/bin/bash
y=00000000
o="$(echo "obase=2; 10" | bc)"
echo "ibase=2;obase=2; $y+$o" | bc -l
But the output still 1010 | You could zero-pad your output with `printf`:
$ printf '%08d\n' $(echo "obase=2; 10" | bc)
00001010 | stackexchange-unix | {
"answer_score": 0,
"question_score": 0,
"tags": "linux, shell script, shell"
} |
Finding multiples of 7 between 2 given integers
I'm trying to return a string (a comma-separated list) of all numbers between two given integers that are multiples of 7. I know how to find the multiples with the modulus operator but not between 2 _given_ numbers. I'm new to JS and learning. Help is greatly appreciated.
Starting with something like this:
function findMultiplesOfSeven(startNumber, endNumber) {
return string;
} | function findMultiplesOfSeven(startNumber, endNumber) {
let containsNumberDivisibleBy7 = false;
let firstNumber;
let numbers = [];
for (var i = startNumber; i <= endNumber; i++) {
if (i % 7 === 0) {
containsNumberDivisibleBy7 = true;
firstNumber = i;
break;
}
}
if (containsNumberDivisibleBy7) {
for (var i = firstNumber; i <= endNumber; i += 7) {
numbers.push(i);
}
}
return numbers.join(",");
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -4,
"tags": "javascript, arrays, string"
} |
How do I turn off try/catch block code completion in ReSharper?
When I start typing a try/catch block, ReSharper causes it to be expanded from
try {
to
try
{
}
catch(Exception)
{
}
I appreciate ReSharper trying to do me a favour, but this is one of those instances where I'd prefer to do it myself seeing as I'm often going back and adding the `try` block later, or typing a `try`/`finally` block without a `catch` clause.
Where do I turn off this behaviour in ReSharper? | ReSharper menu / Live Templates
Under Predefined Templates / C# / Imported Visual C# Snippets
Uncheck try and tryf. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 4,
"tags": "autocomplete, resharper, code completion"
} |
How can I use material graphic elements in a html static page?
I'm developing a static website which will be saved in CDs and USB sticks. It is a manual of a product.
I would to use a graphic framework as onsen ui, but I like material ui more.
I want to use only material ui to create html elements (cards, listtiles, etc...), and all the website will work offline.
Is it possible? How? | You need to check out Materialize CSS. It is CSS + JavaScript library based on Material UI created by Google. It has lots of per-build components Buttons, Badges, Cards, Navbar, Pagination, Floating Action Button. Along with that many per-build CSS classes are provided which you can use to follow Material standards without going into details. Furthermore, you can also visit JavaTpoint which also provides good tutorials on Materialize CSS.
Materialize CSS provides icons as CSS but if you want to download Material Icons as images(raster PNGs or vector SVGs) visit Material.IO | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "html, material ui"
} |
wizard (or an alternative) in an aui managed pane
I would like to have wizard in my application. but I don't want the focus to be on the wizard until the wizard is finished. That's what happens if I use wx.wizard. I prefer to load the wizard in an aui pane. So the user can switch to main window even in the middle of the wizard. I can have panels on top of each to make a wizard. Kindly point me if there is a better Pythonic way of doing that.
Thank you in advance. | The Wizard "widget" in wxPython is basically a dialog. I don't think you can embed it in your application. You might be able to extend the widget somehow to do so, but that would likely be a lot of work.
Instead, I would just create a set of panels that are your wizard pages. You will need a main panel that has some buttons on it that you place your pages on. Then when you hit the button, it will show the next page. I wrote a tutorial on the subject a couple years ago that should get you started:
* < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python 2.7, wxpython, wizard"
} |
How to close connection mysql, mysql.h in c++?
How to close connection in c++ when im using mysql.h library?
MYSQL* conn;
conn = mysql_init(0);
conn = mysql_real_connect(conn, "localhost", "root", "admin", "uczelnia", 3306, NULL, 0); | To close your connection you would use `mysql_close`
MYSQL* conn;
conn = mysql_init(0);
conn = mysql_real_connect(conn, "localhost", "root", "admin", "uczelnia", 3306, NULL, 0);
mysql_close(conn);
> **Description**
>
> Closes a previously opened connection. `mysql_close()` also deallocates the connection handler pointed to by mysql if the handler was allocated automatically by `mysql_init()` or `mysql_connect()`. Do not use the handler after it has been closed. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "c++, mysql"
} |
Memory leaks in android?
This is something that I have noticed in Android. If you restart the phone, you will find that the amount of free memory is more [say 190 mb in the case of HTC Wildfire]. As time passes by, the amount of free memory keeps reducing.
[This free memory I'm refering to is a statistic that i get from a TaskKiller app. I dont trust this app to kill my other applications, but use it to monitor my memory resources.]
Is it something wrong with the app that I am using or are there memory issues in android [for want of a better term].
And if yes, How I as a developer can stop this from happening. | I don't regard them as "issues" since Android is made in such a way that applications keep working in background. call it multi-tasking. and these applications cost you memory. ( I am assuming that you're referring to the RAM size)
When the phone starts, almost all of the apps are sleeping. slowly, background services such as sync and else start up, and they start occupying memory.
That's why you see a drop in free memory. I don't think there's something to worry about, since Android takes care of Memory Management very well.
Although, as a developer, you should create such an app which occupies as less memory as possible. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "android, memory, memory management"
} |
How can I tell (easily) if my power supply is regulated/switched or unregulated/nonregulated?
I found this great blog post about unregulated vs. regulated and switched power supplies. I've got a specialized need for a Regulated 12v power supply and a handful of wall-warts and bricks laying around that I would like to re-use if possible. I have a volt-meter and a handful of basic electronic bits and wires. But I haven't found anything that would help me identify the type of power supply. | Using your voltmeter, just measure the output of the wall-wart without any load. You can generally stick one probe into the middle of the connector, and hold the other against the outside. With a few exceptions, the middle is positive, so use the red lead there, and use the black lead on the outside shell.
Regulated supplies, without any load, should measure very close to the target voltage of 12v. Unregulated supplies will generally have a no-load voltage anywhere from a couple of volts to several volts higher. If they measured 12v without any load, they would have no headroom to take care of the drop due to the load. | stackexchange-electronics | {
"answer_score": 16,
"question_score": 15,
"tags": "power supply, voltage regulator"
} |
Can I output from Lightroom with zero padded numbered names for use in contact cards?
I use lightroom to export photos as it enabled you to use a sequential number, it looks like this:
Flower-1.jpg
The problem is that it doesn't seem to allow any preceding zeros so when I export them to contact cards, they list like this:
1,11,2,22,3,33...
Can I output these in Lightroom with zero padded names or am I stuck trying to so this in Windows directly? | You can actually have them come out with proceeding zeros in Lightroom.
When you go to export, find the File Naming category. From there, make sure "Rename to" is checked and hit the drop down box. Select the last option "Edit...".
!Export image
A box should come up allowing you to enter a formula for how files are named. For numeric sequences it should look something like **{Sequence # (1)»}**. (Note: I couldn't copy and paste the double arrow, so I'm not entirely sure the one I'm using is exactly the same)
!Edit file naming window
You can add preceding zeros to the number inside the parenthesis to get the effect you want.
For instance, I use this: **{Date (YYYYMMDD)»}-{Sequence # (001)»}** So my files come out named like... 20140928-001.jpg, 20140928-002.jpg, etc.
!enter image description here | stackexchange-photo | {
"answer_score": 9,
"question_score": 3,
"tags": "lightroom 4, windows, filenames"
} |
Rename only the last column in pandas dataframe (accounting for duplicate headers)
I need to rename **only** the last column in my dataframe, the issue is **there are many columns with the same name** (there is a reason for this), thus I cannot use the code in other examples online. Is there a way to use something specific that just isolates the final column?
I have tried to do something like this `df.rename(columns={df.columns[-1]: 'Test'}, inplace=True)`
However this then means that all columns with that same header are changed to 'Test', whereas I just want the last one to change.
I kind of need something like `df.columns[-1] = 'Test'` but this doesn't work. | You can always explicitly reassign.
df.columns = [*df.columns[:-1], 'Test']
Or, if you want to method chain, use `set_axis` the same way:
df.set_axis([*df.columns[:-1], 'Test'], axis=1, inplace=False)
* * *
**Minimal Code Example**
df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list('ABA'))
df
A B A
0 1 2 3
1 4 5 6
2 7 8 9
df.rename({df.columns[-1]: 'C'}, axis=1) # wrong
C B C
0 1 2 3
1 4 5 6
2 7 8 9
df.set_axis([*df.columns[:-1], 'Test'], axis=1, inplace=False)
A B Test
0 1 2 3
1 4 5 6
2 7 8 9 | stackexchange-stackoverflow | {
"answer_score": 42,
"question_score": 15,
"tags": "python, pandas, dataframe"
} |
Bypass IE "The webpage you are viewing..." pop up
Is there a way to bypass the following IE popup box:
> The webapge you are viewing is trying to close the window. Do you want to close this window? Yes|No
This is occurring when I add window.close() to the onclick event of an asp.net button control. | Your JavaScript code can only close a window without confirmation that was previously opened by window.open(). This is an intentional security precaution because a script running on a webpage does not own the window, and by closing it discards the browsing history in that window.
The workaround is to either have a "welcome page" or otherwise some sort of page that pops up the window you want to close with window.open in the first place, or to tell your users to modify their browser security settings to allow your application to close their windows. | stackexchange-stackoverflow | {
"answer_score": 11,
"question_score": 11,
"tags": "javascript, asp.net, internet explorer, popup"
} |
`AutoFillTextBox type is not resolvable` why?
I have created a `comboBox`in JavaFx program and I have populated. But Since , there are too many options to be chosen I thought I need to make the user experience more convenient by allowing the them to insert what they're looking for and get it faster in case that options exists . My google search led me to `AutoFillTextBox` .The problem is once I want to use it , it says the type is not defined . Even though I have imported `import java.util.*;`
Any Idea what am I missing ? | import np.com.ngopal.control.AutoFillTextBox;
The problem you are facing seems to be that AutoFillTextBox is not specified in import java.util.*; It is a jar file you have to download:
< | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "java, javafx, combobox, autofill"
} |
Не работают алиасы в vue cli
Проект пишу на **TypeScript**. Добавляю алиасы так:
configureWebpack: {
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'Components': path.resolve(__dirname, './src/сomponents'),
'API': path.resolve(__dirname, './src/api'),
'Mixins': path.resolve(__dirname, './src/mixins'),
},
},
},
Но получаю ошибку при сборке.
> This dependency was not found:
>
> Mixins/application/ApplicationMixin in ./node_modules/cache-loader/dist/cjs.js??ref--14-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/ts-loader??ref--14-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/App.vue?vue&type=script&lang=ts&
>
> To install it, you can run: npm install --save Mixins/application/ApplicationMixin
Так же алиасы не видит **IDE**. Как решить проблему? | Так как я потратил не мало времени, чтобы это заработало, то делюсь опытом. Может кому поможет и сократит время на настройку.
Для того чтобы работали алиасы(например: `Api`,`Components`) и их видел **IDE** (например, **PhpStorm** ) сначало необходимо указать `paths` в `tsconfig.json`:
"paths": {
"@/*": [
"src/*"
],
"Api/*": [
"./src/api/*"
],
"Components/*": [
"./src/components/*"
]
},
А затем продублировать их в `vue.config.js`:
configureWebpack: {
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'Components': path.resolve(__dirname, './src/сomponents'),
'API': path.resolve(__dirname, './src/api'),
'Mixins': path.resolve(__dirname, './src/mixins'),
},
},
},
_Проверено на **@vue/cli 4.5.8**._ | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "typescript, webpack, vue cli, tsconfig"
} |
bootstrap padding from php header
I have made two columns in bootstrap, that should go beneath the header. But this 2 columns are hiding under the header. What is the correct way to make this 2 columns start beneath the header, and not start from the top of the page, where the header should be?
<body>
<?php require 'header.php';?>
<div id="container">
<div="row">
<div class="col-lg-6 bg-warning">
Column 1
</div>
</div>
<div="row">
<div class="col-lg-6 bg-primary">
Column 2
</div>
</div>
</div>
<?php require 'footer.php';?>
</body> | I don't know why you are using php to create a header but the `container` div is probably hiding beneath the header because your header has the CSS style attribute `position:fixed` or `position:absolute`. In order to solve this, assign a margin with the same height as the header. like this:
<body>
<?php require 'header.php';?>
<div id="container" style="margin-top: 70px"><!--INSERT THE HEIGHT OF YOUR HEADER AT THE POSITION OF THE "70"-->
<div="row">
<div class="col-lg-6 bg-warning">
Column 1
</div>
</div>
<div="row">
<div class="col-lg-6 bg-primary">
Column 2
</div>
</div>
</div>
<?php require 'footer.php';?> </body>
Cheers, | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "css, html, twitter bootstrap"
} |
How secure is a 24 character mysql password?
I recently set up my WordPress blog and I changed the password of its mysql database to a 24 character randomly generated password. I have a few questions about the database:
1. Is my database name visible?
2. Does a hacker need both the database name and the password to crack it?
3. How long would it take to brute force it?
I searched Security.SE but couldn't find any specific questions about wordpress sql security. This wordpress.org page explains how databases are created but nothing specific about its visibility. | Your question depends on your setup.
1. I don't know
2. If a potential attacker wants to login to your database, for sure he needs your name as well as your password.
3. If a potential attacker compromises your password hash (let's imagine with a weak hash algorithm, like MD5) he could test about 8-10 billion hashes/s with one Nvidia GTX Titan X (offline).
Let's say you use a 24-character password with `A-Z, a-z, 0-9`. Now the number of combinations can be calculated by `Character-Set^length`. In your case the equation is"
62^24 = 10^43 Combinations (Tredecillion).
If you divide this by 10 billion hashes/s you will get approximately a worst case of 33 septillion years to crack this password.
In other words: no one today is capable of bruteforcing a password with 24 characters hashed with a weak algorithm like MD5. If you use a hash like Sha512 you could reduce the Hashrate of the GPU down to million or thousand hashes/s. | stackexchange-security | {
"answer_score": 0,
"question_score": -1,
"tags": "passwords, password cracking, mysql"
} |
How to choose fields for auditing with Hibernate Envers?
I'm using Hibernate Envers in Spring Boot application with Spring Data. For example, I have a base class
@MappedSuperclass
class BaseEntity {
@Id
private Long id;
// some base fields
// getter and setter
}
And class
@Entity
class Entity extends BaseEntity {
// some fields
// getters and setters
}
**I need to audit only actions that were done and the timestamp of them**. For example, when I create new Entity or update existing Entity object, I want auditing table to contain the following information: **id of entity, time of action, type action**. If I will just add @Audited to Entity class then all fields of Entity will be audited. | You can exclude some fields from being audited by using the @NotAudited annotation like this ...
@Audited
@Entity
class User {
...
@NotAudited
private String phoneNumber;
}
**EDIT:** You can control the schema of the audit table and decide exactly what info to log for each revision by creating a custom revision entity like this
In essence you define a `CustomRevisionEntity` and `CustomRevisionLister` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, spring, hibernate, spring data jpa, hibernate envers"
} |
How to use Linux Work Queue
Linux work queues are meant to be kernel level threads with process context. I was trying to use it as an alternative to kthread which has no specific process context. But how do I pass data to work queue? work_struct has a data field which is of type atomic_long_t. I could not pass pointer to this field. How do I do it?
Also I could not find a single concrete example of work queue. Can you suggest one? | If you want to pass data to your work queue function, just embed the `work_struct` structure inside your own data structure and use `container_of` inside your work function to retrieve it.
As for a simple example, the kernel is full of it - just `git grep work_struct`. You can look at `drivers/cpufreq/cpufreq.c` (`handle_update` function) for a simple example. The article below also embeds an example at the end, but it does not use `container_of` and instead relies on the fact that the first member of a structure has the same address as its parent:
< | stackexchange-stackoverflow | {
"answer_score": 21,
"question_score": 15,
"tags": "linux kernel, kernel"
} |
debian man pages for system calls
I installed debian lenny, but I was quite surprised that I can't get man pages for system calls (`man 2 read`, etc.)
How do I install them? | apt-get install manpages-dev | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 6,
"tags": "linux, debian, manpage"
} |
What will happen if I set ARef to 3.3V and try to use adc connected to 5V
What will happen, if I try to measure voltage higher than ARef? For example, my ref is 3.3V, and I try to measure 4.5V. Will it damage adc? | The datasheet of the Atmega328P does not give a direct answer to this, but
> Single ended channels that exceed V REF will result in codes close to 0x3FF.
(Datasheet Chapter 24.5.2)
sounds, as it would not destroy the ADC, but only result in a value very close to the maximum. I also found another side, where this is also stated. They linked to the Arduino forum, where a similar question is handled in this thread.
So all in all it should be save to provide more than the reference voltage at the ADC pins, as long as it does not exceed the supply voltage (for the UNO 5V).
* * *
As Majenko pointed out in his answer, the datasheet states, that it is safe to provide VCC+0.5V at any pin (except for reset). I just wasn't sure, if this can easily be applied to this special hardware, but it seems, that it can. | stackexchange-arduino | {
"answer_score": 3,
"question_score": 5,
"tags": "arduino nano, adc"
} |
Displaying someting in email template based on a Date value
I am using a visual force template and want to add some logic which will decide whether to display something based on a date field in an Opportunity being less than a certain value.
I try:
<apex:outputPanel rendered="{!IF(relatedTo.opportunity__r.LastModifiedDate > System.now() - 30, true, false)}">Stalled</apex:outputpanel>
I get: Error: Unknown function System.now. Check spelling
Any tips?
Thanks. | I believe all you need to do is replace **System.now()** with **NOW()**. | stackexchange-salesforce | {
"answer_score": 2,
"question_score": 0,
"tags": "email, email template"
} |
mysql indexes : multiple Key_name with the same name
i wanted to see the indexes of a table
SHOW INDEXES FROM images
this is what i got
**Key_name** **Column_name**
user_id user_id
user_id tags
user_id confirm
insert_date_time insert_date_time
insert_date_time category
insert_date_time confirm
i'm confused , why there's so much user_id and insert_date_time under key_name ? i'm pretty sure they are not duplicate .
why there is 2 index for `confirm` under different key names?
i've added the indexes in phpmyadmin by simply clicking on index . | You can name the key whatever you want. In this case you have three keys named `user_id` and three named `insert_date_time`, where two of them in fact are on other columns. Also it seems you have duplicate keys for confirm. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, indexing"
} |
Waiting for update signal from WDS
I am currently trying to create a login page using Twitter authentication for my Vue.js application. I have been following this tutorial and this code. Whenever I run my project, I get
> [HMR] Waiting for update signal from WDS...
Any ideas how I can overcome this WDS error? Thank you.
This is the error I receive in the browser's console. | `[HMR] Waiting for update signal from WDS...` is not an error. HMR: Hot Module Reload. WDS: Webpack Dev Server. This is just saying it's ready to refresh when you save a file so you don't need to manually refresh.
The actual error appears to be present because you're using the `<template>` tag somewhere, but you've got the `runtimeCompiler` option set to `false` in your vue.config.js, or it's not present. So in your vue.config.js, set it to true, or add the option and set it to true.
Documentation source: < | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 10,
"tags": "vue.js"
} |
How do I add an annotation with Django annotate on a QuerySet?
I have a model class with a **status** field, which might have several alternatives, say:
class MyModel(models.Model):
status_choices = (
('status1', 'status1'),
('status2', 'status2'),
('status3', 'status3'),
('status4', 'status4'),
)
status = models.CharField(choices=status_choices)
Then I want to annotate the instances with an `active` field which might be either `True` or `False`. The instance is `active` when status is IN [status1, status2].
Django version is 1.11. | We can do this with a [**`Case`** expression [Django-doc]](
from django.db.models import BooleanField, Case, Value, When
MyModel.objects.annotate(
active=Case(
When( **status__in** =['status1', 'status2'], then=Value(True))
default=Value(False),
output_field=BooleanField()
)
)
Note that the list of the `status__in` condition should contain the _keys_ of the choices (so the left item of the tuples, not the right one). | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "django, django queryset"
} |
Merge two tables and keep smaller value in R
I have two tables and want to keep the smaller values of `FC` and `FH` for common `Tasks`. Tables look like this:
x <- data.frame("Task" = c("A","B","C","D","E"),
"FC" = c(12,NA,15,14,NA),
"FH" = c(13,15,NA,17,20))
Task FC FH
1 A 12 13
2 B NA 15
3 C 15 NA
4 D 14 17
5 E NA 20
y <- data.frame("Task" = c("B","C","F","G"),
"FC" = c(NA,12,20,NA),
"FH" = c(NA,17,18,NA))
Task FC FH
1 B NA NA
2 C 12 17
3 F 20 18
4 G NA NA
How can I use the function `melt` to get a result like this:
Task FC FH
1 A 12 13
2 B NA 15
3 C 12 17
4 D 14 17
5 E NA 20
6 F 20 18
7 G NA NA | A `data.table` solution would be
# Bring together the two tables
z <- funion(as.data.table(x),as.data.table(y))
# Find the min of FC and FH for each Task
z <- z[, .(FC = min(FC, na.rm = T), FH = min(FH, na.rm = T)), by = "Task"]
# Replace Infs returned by min with NA
z[is.infinite(FC), FC := NA]
z[is.infinite(FH), FH := NA] | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "r, dataframe, merge"
} |
Why IViewLocalizer no working with keyword {0}?
I have an asp.net core 5 project with `IViewLocalizer` for Localizer.
The string in Localizer has some dynamic keyword, it is used for component view.
I am about to use `String.Format` to solve this.
So I have to add some variable string in the localizer, for example:
Welcome to {0}
When I use the code below to render it in the view:
@string.Format(Localizer["Welcome"].Value, ShopName)
This string doesn't render any and blocks all the code after it.
It is so strange that Visual Studio 16.8.2 doesn't report any errors.
Soon I found a solution with this:
@Html.Raw(string.Format(Localizer["Welcome"].Value, ShopName))
However, I don't know what causes this problem and why `Html.Raw`solves it.
Could you please tell me more about this? Thank you. | Can You try like this when you get data from localizer;
@Localizer.GetString("Welcome",new string[]{"Shop Name"}); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "asp.net core, .net 5, asp.net core 5.0"
} |
Bash variables quoted in the index field of an associative array reference?
`"${array[$key]}"` vs `"${array["$key"]}"`?
Typically I quote all bash variables as a default, with purposed exceptions. What about when specifying a key for an associative array? I see that in simple cases, keys can have spaces and there doesn't seem to be any word splitting issues without quotes, but shell frequently has obscure situations where constructs have caveats.
There are lot of extra characters in `"${array[$key]}"` and moreso `"${array["$key"]}"`. Is there any reason it would be a bad habit to leave variables unquoted in the index field of an associative array reference? | Variables in a subscript of an associative array need not be quoted.
If double quotes _are_ used, they will be removed (whether the entire array variable is also quoted, or not). So you can double quote if you want, but it doesn't do anything.
Single quotes _will_ stop expansion of the variable (containing the array subscript), as normal.
`man bash` > `Arrays`
>
> associative arrays are referenced using arbitrary strings
>
Also note, _indexed_ arrays subscripts are evaluated as arithmetic, meaning `$` is not necessary for variables used in the subscript. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "bash"
} |
git pull fails in 75% of cases when 20 attempts made at once
I have a central server and when I need to do a batch task I launch a number of AWS instances simultaneously. During startup they call git pull (master is the central server) to get their version of the codebase up to head, so I often have 20 (or many more) pull requests at once.
Recently the delta between the instance's starting image and head has become fairly large, and now a large percentage of the instances will have the pull fail with:
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.Please make sure you have the correct access rights
and the repository exists.
I can alleviate the issue by staggering the launching of the instances and keeping their image closer to head, but I would like to solve this issue for good - any ideas? | You are hitting both `MaxSessions` and `MaxStartups` limits. Edit your /etc/sshd_config to this values and it will work after you reload sshd config.
# The number of simultaneous git pull you have
MaxSessions 20
# MaxStartups this tells when sshd will start dropping unauthencicated sessions (% drop)
# Values: When_to_start_dropping_sessions:initial_rate:max_unauthenticated_sessions
# Set to MaxSessions-2*MaxSession:10:HugeNumber (defaults to 10:30:100).
MaxStartups 40:10:200 | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "git"
} |
Invalid identifier, cakephp 2.5 relationship
I am using cakephp 2.5, and I get an error message :
> Warning (2): ociexecute(): ORA-00904: "USER"."UF": invalid identifier [ROOT\app\Model\Datasource\Database\Oracle.php, line 432]
At the controller I do have this conditions asking for the user uf column
//Verify controller
$paginate['conditions']['User.uf'] = $this->passedArgs['Verify.uf'];
$paginate['contain'][] = 'User';
At the model I do have a belongsTo property with the user relationship:
//Verify Model
public $belongsTo = array(
'User' => array(
'className' => 'Usuario',
'foreignKey' => 'user_id',
),
How can i relate the User Model with the Verify Model? | Add the Containable behavior to the model class.
$actsAs = array('Containable');
You can also load the behavior on the fly:
$this->Verify->Behaviors->attach('Containable'); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "cakephp"
} |
Hadoop Hive query to merge rows into one row
I need one hive query which merge same EAN rows into one record in table based on priority which is another table.
table: products  and I want only one row by merging all sources data based on below priority. If priority "1" source doesn't provide any field info, that field info will be taken from priority "2" source.
Table: priority
node_id Source_id Priority
1 62 1
1 303 2
1 202 3
I am expecting results as shown below.
.ready(function() {
$('.answer').hide();
$(".toggle").click(function(){
$("div[rel='profile_" + $(this).attr("profile") + "']").toggle(400);
});
}); | You should add
$(".answer").not($(this).next()).hide(400);
before you call the `toggle()` function
**Side notes**
1. You could change the line `$("div[rel='profile_" + $(this).attr("profile") + "']").toggle(400);` to `$(this).next().toggle(400);`
2. Instead of using the attribute `profile` you should better use the `data` attribute
**Demo** | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "jquery"
} |
how to customize CMenu widget in Yii
How can I set CMenu to dropdown in Yii framework project to display like what is in < website. | There's a good demo here: Creating a CSS Driven Drop Down Menu using CMenu about creating a nice dropdown menu using CMenu. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "drop down menu, yii, cmenu"
} |
Why is Scala Map auto-imported but HashMap isn't?
If we use map then no need to import immutable **map**
scala> val map=Map[String,Int]()
map: scala.collection.immutable.Map[String,Int] = Map()
But if we use HashMap, then without doing import, it gives error.
scala> val a=HashMap[Int,Int]()
<console>:7: error: not found: value HashMap
val a=HashMap[Int,Int]()
^
but doing import scala.collection.immutable.HashMap, it works.
I also see it with Set and Hashset..
I notice one thing that Map and Set are trait and HashSet,HashMap are classes.
So Why it is so ???
**EDIT**
Class Stack and Queue is also exist in scala.collection package. then why do we need to import these classes. ??? | _Program to an interface, not an implementation_. Scala designers encouraged this by providing shortcuts to interfaces in Predef. | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 5,
"tags": "scala, scala collections"
} |
How can I print many pre-existing strings separated by a line?
I'm working on a project and I have a bunch of already defined strings with various names
I want to print all of them, each one starting on a new line. What I have right now is this:
print(line1 + '\n' + line2 + '\n' + line3 ... )
Don't get me wrong, it works, but I was just wondering if there was an easier way to do it that would physically shorten the line. Thanks! | You can use the `.join` method:
>>> line1 = "a"
>>> line2 = "b"
>>> line3 = "c"
>>> "\n".join([line1, line2, line3])
'a\nb\nc'
>>> print("\n".join([line1, line2, line3]))
a
b
c
Or, you can use the `sep` parameter of `print` if you don't need to store the string:
>>> print(line1, line2, line3, sep="\n")
a
b
c | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python"
} |
xcode duplicates in arrray
I have a NSArray with some "towns" in it (get these towns from a json database), but there are some towns 2 or 3 times in the array and I have to delete these towns.
How can I solve this problem? with a for-loop or a spezific function in x-code?
please help! | one line solution, you need to add autorelease for non-ARC project
NSArray *array = // your array
NSArray filteredArray = [[[NSOrderedSet alloc] initWithArray:array] array]; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -4,
"tags": "iphone, xcode, arrays, nsarray"
} |
How to get rid off html tags in JSF to return only JSON?
If I have the following only, what should I do to get only the jsf expression data output without any other stuff?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"
<html xmlns="
xmlns:ui="
xmlns:h="
xmlns:f="
#{backingBean.jsonData}
</html> | Just don't output `<!DOCTYPE>` and `<html>` then.
<ui:composition xmlns:ui="
#{backingBean.jsonData}
</ui:composition>
That said, you're here basically abusing JSF, a component based MVC framework, as a JSON web service. This is a very bad design approach as in "using the wrong tool for the job". I strongly recommend to take a look at JAX-RS, which is the right tool for the job. Jersey has a very nice tutorial. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "json, jsf"
} |
Can there be a homeomorphism of $[0,1]$ that maps $\mathbb Q$ to the dyadic rationals?
Can there be a homeomorphism of $[0,1]$ to itself that maps $\mathbb Q$ to the dyadic rationals?
What I know is that homeomorphisms of $[0,1]$ have to be increasing or decreasing and map endpoints to endpoints. I see there is a certain struction to the dyadic rationals which $\mathbb Q$ doesn't have but I can't see if that's a problem or not. | Let $Q=\Bbb Q\cap[0,1]$ and $D$ be the set of dyadic rationals in $[0,1]$. $Q$ and $D$ are countable dense linear orders with endpoints, so they are order-isomorphic. Let $h:Q\to D$ be an order-isomorphism. $[0,1]$ is the Dedekind completion of each of these sets, so $h$ extends to an autohomeomorphism of $[0,1]$ | stackexchange-math | {
"answer_score": 8,
"question_score": 3,
"tags": "general topology"
} |
Defining Application Constants in Codeigniter
I want to know a clean way of defining Application Constants in Codeigniter. I don't want to change any native file of codeigniter. Hence I don't want to define it in `application/config/constants.php` as when I need to migrate to newer version of code-igniter I will not be able to copy the native files of codeigniter directly.
I created a file `application/config/my_constants.php` and defined my constants there. 'define('APP_VERSION', '1.0.0');'
I loaded it using `$this->load->config('my_constants');`
But I am getting a error
`Your application/config/dv_constants.php file does not appear to contain a valid configuration array.`
Please suggest me a clean way of defining application level constants in code-igniter. | Not using `application/config/constants.php` is nonsense! That is the **only place** you _should_ be putting your constants. Don't change the files in `system` if you are worried about upgrading. | stackexchange-stackoverflow | {
"answer_score": 39,
"question_score": 12,
"tags": "php, codeigniter"
} |
How to use focus() event in mozilla firefox?
I have used `focus()` method, but it does not work on Mozilla Firefox. I have used the following code in asp .net:
protected void drgBranches_SelectedIndexChanged(object sender, EventArgs e)
{
txtLoginName.Text = drgBranches.SelectedValue;
txtLoginName.Focus();
} | You can just the regular focus
<input id="target" type="text" value="Field 1">
$("#target").focus(function() {
alert( "Handler for .focus() called." );
});
< | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "html, asp.net"
} |
How to link Ebean subquery to main query
I need to find all users that have some money on their accounts and who have not been logging in for a long time. That's what I do:
Query<UserSessionRecord> subQuery =
Ebean.createQuery(UserSessionRecord.class)
.where().gt("loginDateTime", DateTime.now().minusMonths(1))
.eq("user", "user") // <-- here I need to refer somehow to the main query
.query();
//my main query
List<User> users = User.FIND.where().eq("account.balance", 0)
.notExists(subQuery)
.orderBy("id").findList();
This code doesn't work because the field user in UserSessionRecord is an entity User (not a String). How can I refer to the user in subquery? | You can give your user table a SQL alias. Then you can check equality using the raw()-method.
Query<UserSessionRecord> subQuery =
Ebean.createQuery(UserSessionRecord.class)
.where().gt("loginDateTime", DateTime.now().minusMonths(1))
.raw(mainuser.id=user.id)
.query();
List<User> users = User.FIND.query().alias("mainuser").where().eq("account.balance", 0)
.notExists(subQuery)
.orderBy("id").findList(); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "playframework, ebean"
} |
Support for RTP/RTSP in WebAssembly
I have a C++ code which provides a live RTP/RTSP video stream and want to transpile that code to web assembly. So, before doing that I want to know whether web assembly support RTP/RTSP Live streaming or I have to make Changes in my Code for Live Streaming? | WebAssembly is a simple assembly language, it supports computations based on a few core types, and that's it! You can export WebAssembly functions to make them callable by JavaScript, and import JavaScript functions to make them callable from WebAssembly (with type restrictions).
So no, it does not support RTP/RTSP - it is likely that you will have to do quite a bit of work to make this work. One option is to use WebSockets to stream the data, then handle the protocol logic within WebAssembly. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "webassembly"
} |
What is the difference between 太太 and 夫人?
What is the difference between and ? My book () translates it as the same word. “Woman (married)” and it says they can both be a suffix as well as a noun.
**Question** : Is there really no difference between the two? | In modern Chinese:
is a common title for "Mrs." or a noun for "married woman" (in general)
> **Mrs.** : _a title used before a surname or full name to address or refer to a married woman, or a woman who has been married, without a higher or honorific or professional title._
is a more formal honorific or title for "Madam" or a noun for "married woman" (of high status)"
> **_Madam** :(often initial capital letter) a polite term of address to a woman, originally used only to a woman of rank or authority:_
In short, is a general title for married women; is a more formal/honorable title for married women;
_ is another honorific for women. A formal/ polite term for addressing to adult woman (single or married)_
_The difference between and is somewhat similar to San () and Sama () in Japanese_ | stackexchange-chinese | {
"answer_score": 3,
"question_score": 4,
"tags": "word choice, difference, gender"
} |
How to calculate the distance between a document and each centroid (k-means)?
I executed scikit-learn k-means algorithm and got the resulting centroids. I have a new document (was not in the initial collection) and I would like to calculate the distance between every centroid and the new document to know in which cluster it should be placed.
Is there a built in function to achieve that or should I write a similarity function manually? | You can use the method `predict` to get the closest cluster for each sample in a matrix `X`:
from sklearn.cluster import KMeans
model = KMeans(n_clusters=K)
model.fit(X_train)
label = model.predict(X_test) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, machine learning, scikit learn, cluster analysis, k means"
} |
Does reputation in one community affect reputation in other communities?
I started using Stack Exchange not long ago. I noticed that the initial community I joined I quickly lost the ability to ask questions. In other communities I had no trouble and am using regularly. Maybe it was my initial lack of knowledge in using the system that got me banned in one community (in terms of asking questions). My question is: Does my reputation in other communities in any way help or not in a community where I cannot ask questions? | Looks like you are asking the following:
Can participation in other Stack Exchange sites affect a question (or answer) ban on another specific site?
The answer to that is: No.
In order to get out of a question (or answer) ban on a site, you need to positively participate on that site by giving good answers, asking good questions, and/or providing good suggested edits to posts. | stackexchange-meta_stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "support, questions, asking questions"
} |
I want to get the parents id from my container in flex
I have an issue, so i created a mxml container file called Container1.mxml that has
`<mx:VBox>`
`<mx:Label text="{textName}" />`
`</mx:VBox>`
so when i call it it will be something like
`<container:Container1 id="hello" />`
then the id will appear in my Label text.
appreciate it in advance. thank you | Assuming you can't just use `text="{this.id}"`?
Inside Container1.mxml, have a creation complete listener that calls this function:
protected function _handleCreate(e:Event):void {
myTextLabel.text = this.id || "unknown";
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "apache flex, actionscript 3, flex4"
} |
Access server variable in client side (node.js + express)
I have a simple html page being served by express on a node.js server and in the client side javascript i want to access some server side variables. I tried googling around for a solution but didn't see a straight forward solution without using some sort of templating engine.
So if i need to access a variable on the server from a client side JS served from the same host, what do i need to do? | To access the variable on the client, you'll need to expose it inside of a script tag, there are a few node modules that can help you with it (ex: express-state) < but you'll need a templating engine to generate the html required for it. You can use a variety of templating engines when working with express. If you use express generators straight out of the box it should come with jade and you can use different options on the generators to use other templating engines. See here for express generator options < | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "javascript, node.js, express"
} |
.htaccess block access to files
Using an `.htaccess` file, how can I block access to a folder and all of it's files? I know I can do `Options -Indexes` but that still allows someone to access the files in the directory and download them. I would like to also disable access to the files as well. Basically I want to make a storage spot in the website to store the PDF files used to create the images or anything else that I don't want the outside world to access. | Order deny,allow
Deny from all | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "apache, .htaccess"
} |
Finding derivative with integral
. How is it sin(x)? Or did I come across another error? At this point In this class I never know anymore. | This is the second fundamental theorem of calculus, which states that if a function $F$ is continuous on open interval $I$ and $a \in I$ with $F(x)=\int_a^x f(t)\,dt $ then $F'(x)=f(x)$
You can verify it by first evaluating $\int_\pi^x \sin \theta \, d\theta $, then taking the derivative with respect to $x$. i.e. $$\int_{\pi }^x \sin \theta \, d\theta = - \cos x -(- \cos \pi)= -\cos x-1 \\\ \Rightarrow g'(x) = \frac{d}{dx} (-\cos x -1 ) = \sin x$$ | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "calculus, integration, derivatives"
} |
Place Marker on center of polyline
i am using Google's direction service alongside the Polyline class to draw lines along a road with custom colors. I want to be able to place a market on the center of a polyline. I have tried using the following code:
function Marker(start, end) {
var midP = google.maps.geometry.spherical.interpolate(start, end, 0.5);
// console.log(map);
// console.log(midP);
var options = {
position: midP
};
marker = new google.maps.Marker(options);
marker.setMap(map);
}
start and end are the start and end points of a given polyline.
However the marker doesn't fall on the polyline. It appears to untill you zoom in. I would appreciate any help on how to get this right. Thanks | I think what you're looking for is the _midpoint_ of the polyline, i.e. the point at which you would have traveled have the distance following the route. Is that right?
Then I would use an algorithm like this one which finds the midpoint of a polyline. The code in that answer is written for a polyline "defined as a series of [x,y] points", but could easily be adapted to use a Maps API polyline. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "google maps api 3"
} |
Solve the datarow code?
Below code raise error
DataRow[] dr = dt.Select("" + ColumnName + "='" + strLetter + "'" + " order by asc");
error is
> Missing operand after 'order' operator. | There is no column name to sort, you need to pass column name which you need to sort
DataRow[] dr = dt.Select("" + ColumnName + "='" + strLetter + "'" + " order by " + ColumnName + " asc"); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -2,
"tags": "c#, string, datarow"
} |
Unable to run typescript build task: 'C:\Program' is not recognized as an internal or external command
I am trying to compile typescript code to JavaScript by following the documentation.
I created the watch task to compile the .ts files on pressing `Ctrl+Shift+B`. However, I get the error after I run the task:
> 'C:\Program' is not recognized as an internal or external command
I understand the cause of the error, as the directory `Program Files` has spaces in it, and I need quotes around it.
How do I update the build command to run the compiler with proper path?
, but you need to detect when the quote starts, when the quote ends, then search that specific string for separator characters. How?
I've experimented with some Regexs but I just keep getting myself confused!
Any ideas? Even just something to get the ball rolling, I'm just completely stumped. | string pattern = "\"([^\"]+)\"";
value = Regex.Match(textToSearch, pattern).Value;
string[] removalCharacters = {",",";"}; //or any other characters
foreach (string character in removalCharacters)
{
value = value.Replace(character, "");
} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 5,
"tags": "c#, regex, string, text files"
} |
How do I use a small die to get a larger, linearly-distributed random number?
Say I have a coin, aka 1d2, aka a 2-sided die. I need to get a random integer from 1 to _n_ with equal probability of all _n_ integers. I can flip/roll my coin/1d2 as many times as I need to (within reason/practicality).
How can I use a coin/1d2 to get, say, an evenly/linearly distributed random number from 1 to 6?
My initial approach is to simply roll 6 times and add up the number of times I get heads/1, and ignore any tails/2 values. But over multiple iterations this yields a (gaussian?) distribution matching a bell curve; 3 is most likely, followed by 2 and 4, then 1 and 5, and least likely 0 and 6 (which is another problem; the result can be 0).
I'll accept something that's a close approximation to equal probability, provided the procedure works for multiple values of _n_ and not just 6. | There are lots of ways to do this, some less efficient than others. Powers of $2$ are easy, because for $1$ to $4$, for example, you can assign $1,1\to 1$; $1,2\to2$; $2,1\to3$; and $2,2\to4$. If you wanted to do $1$ to $3$, you can use the same method, but let $2,2$ map to "start over." Generalize this idea to $n$. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "probability distributions, random, dice"
} |
WordPress: if post time is after a specific date
I'm trying to add to this if statement another one that checks if post time is before a specific date (let's say 14th March 2014..).
<?php if (in_category('5')) {
echo 'something'; }
?>
I tried with this but it's echoed even on posts newer than that date
<?php
$date1 = "2014-03-14";
$date2 = $post->post_date;
if ( (in_category('5')) && ($date1 < $date2) ) {
echo 'something';
}
?> | I'd convert your dates to timestamps first to make them easier to compare.
global $post;
$compare_date = strtotime( "2014-03-14" );
$post_date = strtotime( $post->post_date );
if ( in_category(5) && ( $compare_date > $post_date ) ) ...
It looks like you have your operator the wrong way round as well. You wanted to check if posts are before the date. The post date would have to be smaller to be before. Also you're passing in category ID 5 as a string for some reason which I corrected in my code above. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "php, if statement, wordpress"
} |
How I get the current location(frame) from a UITableViewCell?
I want to make a custom transition(with `UIViewControllerAnimatedTransitioning`). So I present a `UIViewController` modally and then I add a `UIImageView` (to the transition containerView) and set its frame to the selected cell´s frame.
It all works fine, but the frame is not correct, the `UIImageView` is not exactly over the `UITableViewCell` and if I select a cell from the bottom the `UIImageView` starts animating from "start frame" of the cell.
I think I have to update the frames somehow but how? | I think the solution for the misplaced frame can be found in the answer presented by Nick Weaver in this question: Get UITableviewCell position from "visible" area or window | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ios, uitableview, animation, uiimageview"
} |
Java Runtime Process Won't "Grep"
I'm executing some commands from the command line in my java program, and it appears that it doesn't allow me to use "grep"? I've tested this by removing the "grep" portion and the command runs just fine!
My code that DOESN'T work:
String serviceL = "someService";
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("chkconfig --list | grep " + serviceL);
Code that does work:
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("chkconfig --list");
Why is this? And is there some sort of correct method or workaround? I'm aware that I could just parse the entire output, but I would find it easier to do it all from the command line. Thanks. | You're trying to use piping which is a function of the shell ... and you're not using a shell; you're exec'ing the `chkconfig` process directly.
The easy solution would be to exec the shell and have it do everything:
Process proc = rt.exec("/bin/sh -c chkconfig --list | grep " + serviceL);
That being said ... why are you piping to grep? Just read the output of `chkconfig` and do the matching yourself in java. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 5,
"tags": "java, linux, process, runtime, grep"
} |
Error in file uploading in php
My HTML code
<form method="post" enctype="multipart/form-data" action="upload.php">
<input type="file" name='image' >
<input type="SUBMIT" value="Submit">
</form>
PHP code(Only the line which is errorneous is mentioned)
<?php
list($waste,$extension) = explode("/",$_FILES["image"]["type"]);echo $extension;
?>
It is giving file extension if the file is an image but it's giving error in case of video.
**ERROR**
( ! ) Notice: Undefined index: image in D:\wamp\www\upload.php on line 3
Call Stack
# Time Memory Function Location
1 0.0007 364904 {main}( ) ..\upload.php:0
( ! ) Notice: Undefined offset: 1 in D:\wamp\www\upload.php on line 3
Call Stack
# Time Memory Function Location
1 0.0007 364904 {main}( ) ..\upload.php:0
Please tell me how to make it work for video uploading also. | The ini_set function is
ini_set("max_filesize","150M"); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -5,
"tags": "php, html"
} |
Developing an Spring Boot application with Angular2 TypeScript in Idea: gradle processResources wathing mode wanted
I am developing a Spring Boot application in IntelliJ Idea with Angular2 TypeScript UI with Gradle build system. When I run my program from IntelliJ Idea. In the background I run a `npm run tsc:w`.
details from package.json:
"scripts": {
...
"tsc": "tsc",
"tsc:w": "tsc -w",
...
},
As I change the typescript code, the new code isn't available from webapp, until I run a `gradle processResources` in command line.
I think the problem is that the Spring Boot app serves the file from the build direcory not from the resources library.
Are there a watching possibility in gradle processResources like in the typescript compiler? | I have found the solution:
`gradle processResources -t`
watches for changes and reprocess them if necessary. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "intellij idea, gradle, spring boot, npm"
} |
How to set a download counter on Hyperlink Control inside Repeater? asp.net
I have a hyperlink inside a repeater control for the list of pdf. I want to set a download counter on each click on each hyperlink. The FileName must be a parameter. My code is basically like below. There is also code that calls stored procedure and bind it to the repeater on page_load.
<asp:Repeater ID="rptPDF" runat="server">
<ItemTemplate>
<div class="repeaterResources">
<b><%# Eval("Name") %></b><br />
<b>Description</b> <%# Eval("Description") %><br />
<asp:HyperLink ID="HyperLink2" runat="server" class="downloadLink" NavigateUrl='<%# "~/PDF/" & Eval("Filename") %>' Target="_blank">Download</asp:HyperLink><br /><br />
</div>
</ItemTemplate>
</asp:Repeater>
The mystery bit is how to get a button click event from here. Thanks. | You can use the OnCommand event and set the CommandArgument attribute with a value using
`<%# Eval('myvalue') %>`.
MSDN has an example minus the repeater: <
Sample:
<asp:Repeater ID="repeater" runat="server">
<ItemTemplate>
<asp:LinkButton runat="server" ID="button1" OnCommand="button1_command" CommandArgument='<%# Eval("myvalue") %>' />
</ItemTemplate>
</asp:Repeater> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "asp.net, vb.net, hyperlink, repeater, asprepeater"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.