text
stringlengths 464
37.4k
| meta
dict |
|---|---|
Q:
Awk pattern matching
I want to print
userId = 1234
userid = 12345
timestamp = 88888888
js = abc
from my data
messssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
<input name="userId" value="1234" type="hidden"> messsssssssssssssssssss
<input name="userid" value="12345" type="hidden"> messssssssssssssssssss
<input name="timestamp" value="88888888" type="hidden"> messssssssssssss
<input name="js" value="abc" type="hidden"> messssssssssssssssssssssssss
messssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
How can I do this with AWK(or whatever)? Assume that my data is stored in the "$info" variable (single line data).
Edit : single line data i mean all data represent like this
messss...<input name="userId" value="1234" type="hidden">messsss...<input ....>messssssss
So i can't use grep to extract interest section.
A:
I'm not sure I understand your "single line data" comment but if this is in a file, you can just do something like:
cat file
| grep '^<input '
| sed 's/^<input name="//'
| sed 's/" value="/ = /'
| sed 's/".*$//'
Here's the cut'n'paste version:
cat file | grep '^<input ' | sed 's/^<input name="//' | sed 's/" value="/ = /' | sed 's/".*$//'
This turns:
messssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
<input name="userId" value="1234" type="hidden"> messsssssssssssssssssss
<input name="userid" value="12345" type="hidden"> messssssssssssssssssss
<input name="timestamp" value="88888888" type="hidden"> messssssssssssss
<input name="js" value="abc" type="hidden"> messssssssssssssssssssssssss
messssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
quite happily into:
userId = 1234
userid = 12345
timestamp = 88888888
js = abc
The grep simply extracts the lines you want while the sed commandsrespectively:
strip off up to the first quote.
replace the section between the name and value with an "=".
remove everything following the value closing quote (including that quote).
A:
This part should probably be a comment on Pax's answer, but it got a bit long for that little box. I'm thinking 'single line data' means you don't have any newlines in your variable at all? Then this will work:
echo "$info" | sed -n -r '/<input/s/<input +name="([^"]+)" +value="([^"]+)"[^>]*>[^<]*/\1 = \2\n/gp'
Notes on interesting bits:
- -n means don't print by default - we'll say when to print with that p at the end.
-r means extended regex
/<input/ at the beginning makes sure we don't even bother to work on lines that don't contain the desired pattern
That \n at the end is there to ensure all records end up on separate lines - any original newlines will still be there, and the fastest way to get rid of them is to tack on a '| grep .' on the end - you could use some sed magic but you wouldn't be able to understand it thirty seconds after you typed it in.
I can think of ways to do this in awk, but this is really a job for sed (or perl!).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to force html elements into one line?
I have some elements like:
<div>
<div style="overflow: hidden; white-space: nowrap; text-overflow:ellipsis">
Texttttttttttttttttttttttttttttttttttttttttttttttttttttttttt
<div style="float: right">Float text</div>
</div>
This will display something like:
Texttttttttttttttttttttttttttttttttttttttttttt...
Float text
However I want it to be like:
Texttttttttttttttttttttttttttttttttttt...Float text
I try to use the absolute position method, but in this way, the ellipsis will not be shown.
Is there any way I can do this?
NOTICE:
Not sure what's wrong, but many people suggest with the inline block or span way, both doesn't work. While putting the float text before 'Textttt' DOES work.
A:
Put the right-floated block BEFORE the text you want it to be in line with.
<div style="overflow: hidden; white-space: nowrap; text-overflow:ellipsis">
<div style="float: right">Float text</div>
Texttttttttttttttttttttttttttttttttttttttttttttttttttttttttt
</div>
https://jsfiddle.net/pkfwnan7/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
change space between ticks in first y-axis in plt.imshow
Hey I have used the following code:
import matplotlib.pyplot as plt
import numpy as np
Class1=np.array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [0., 0., 1., 0., 0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 1., 0., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [0., 0., 0., 0., 0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 1., 1., 1., 0., 1., 1., 1., 0., 1., 0., 1., 0., 1.], [0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 1., 0., 0., 1., 1., 1., 0.]])
Unique=np.array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.,
13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25.,
26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38.])
counts=np.array([56184982, 2904400, 4950837, 114746, 4270, 182052,
844444, 106292, 47007, 68480, 23522, 13838,
23990, 301704, 50462, 21345, 12263, 7217,
64194, 251, 885, 2947045, 4895643, 102992,
4401, 180136, 844872, 281, 107200, 48703,
69791, 22651, 50295, 22772, 7020, 62543,
43, 1103, 48])
list_y2=[]
list_x=[]
list_y1=[]
for i in np.arange(len(Unique)):
list_y2.append( np.array2string(round(counts[i]/Class1.sum(axis=1)[i],2)))
if i < 9:
list_x.append(str(i+1))
else:
list_x.append( str(i+1))
list_y1.append( str(38-int(Unique[i])))
fig, ax1 = plt.subplots()
F=16
ax1.set_xlabel('Brain image',fontsize=F)
ax1.set_yticks(np.arange(len(list_y1)))
ax1.set_yticklabels(list_y1)
ax1.set_xticks(np.arange(len(list_x)))
ax1.set_xticklabels(list_x)
ax1.set_ylabel('class',fontsize=F)
ax2 = ax1.twinx()
ax2.set_yticks(np.arange(len(list_y2)))
ax2.set_yticklabels(list_y2, va='baseline')
ax2.set_ylabel('size',fontsize=F)
#Rotate the tick labels and set their alignment.
plt.setp(ax1.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
plt.imshow(Class1, aspect='auto')
fig.tight_layout()
plt.show()
which makes the following plot:
The problem with this is that the first y-axis doesn't fit the plot properly. The length between the ticks in the first y-axis should be the same as in the second y-axis and the 0 in the top and the 38 in bottom should be moved a bit inward on the y-axis. Hope one of you can help me.
A:
I had the same problem recently and found the following workaround: Setting the same limits for the twin axis ax2 as for the parent axis (ax1). This aligns the ticks on both y-axes and then you proceed by setting the ticks and the labels as desired as you are doing.
ax2 = ax1.twinx()
ax2.set_ylim(ax1.get_ylim()) # This was the fix for me
ax2.set_yticks(np.arange(len(list_y2)))
ax2.set_yticklabels(list_y2, va='baseline')
ax2.set_ylabel('size',fontsize=F)
Let me know if it works.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cross product of records in AWK using Joins
I have a dataset with 1994 records with 13 fields. I am trying to get the cross product of the dataset below:
Dataset
c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13
1 2 5 6 7 3 1 8 5 9 7 3 4
2 4 . . . . . . . . . . .
3 9 . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
1994 . . . . . . . . . . . .
output of the cross product would be each record in the dataset in parallel(in continuous column) with all the other records in the dataset. like shown below:
Expected output
c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 c16 c17 c18 c19 c20 c21 c22 c23 c24 c25 c26
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
When I execute the code : join file{,} -j99 I get both the records of cross product one underneath another.
If I apply the same code for records less than 10 then the output is as expected. I tried to change the value of -j to 99999 and 9999999 but no change in the output.
I get output as:
c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13
. . . . . . . . . . . . .
. . . . . . . . . . . . .
So, I have 1994 records, I should get : 1994*1994 = 3,976,036, but I get twice of those rows as the records are one underneath another.
A:
A cross join is every row for each row. So tell awk to print the whole file next to each line. Something like
#!/usr/bin/awk -f
{
cmd = "awk -v LINE='" $0 "' " "'{ printf(\"%s\\t%s\\n\", LINE, $0) }' " \
FILENAME
system(cmd)
}
But I would never do this. It's inefficient, invoking awk O(N) times, and it doesn't get you much. I'd import the file into SQLite and use a cross join that gave me a where clause and named columns.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Segregating array of objects based on hour-wise from time-stamp attribute
I have an array of objects which has be combined based on each hour-wise. For example:
[{"id": "12345", "data": "abc", "timestamp": "2017-10-17T00:05:30.523Z"},
{"id": "16375", "data": "sgr", "timestamp": "2017-10-17T00:23:54.234Z"},
{"id": "46537", "data": "etd", "timestamp": "2017-10-17T01:36:16.463Z"},
{"id": "83645", "data": "eth", "timestamp": "2017-10-17T01:32:25.640Z"},
{"id": "36153", "data": "her", "timestamp": "2017-10-17T01:56:13.478Z"},
{"id": "31383", "data": "sry", "timestamp": "2017-10-17T05:56:56.362Z"},
{"id": "68123", "data": "rya", "timestamp": "2017-10-17T06:34:30.652Z"}]
I want the resultant data in the following format:
{ "00:00-00:59":
[{"id": "12345", "data": "abc", "timestamp": "2017-10-17T00:05:30.523Z"},
{"id": "16375", "data": "sgr", "timestamp": "2017-10-17T00:23:54.234Z"}]
"01:00-01:59":
[{"id": "46537", "data": "etd", "timestamp": "2017-10-17T01:36:16.463Z"},
{"id": "83645", "data": "eth", "timestamp": "2017-10-17T01:32:25.640Z"},
{"id": "36153", "data": "her", "timestamp": "2017-10-17T01:56:13.478Z"}]
"05:00-05:59": [{"id": "31383", "data": "sry", "timestamp": "2017-10-17T05:56:56.362Z"}]
"06:00-06:59": [{"id": "68123", "data": "rya", "timestamp": "2017-10-17T06:34:30.652Z"}]
Is it possible to format the data as mentioned above? How can I write a short code for the requirement?
A:
try this code
var a = [{"id": "12345", "data": "abc", "timestamp": "2017-10- 17T00:05:30.523Z"},
{"id": "16375", "data": "sgr", "timestamp": "2017-10-17T00:23:54.234Z"},
{"id": "46537", "data": "etd", "timestamp": "2017-10-17T01:36:16.463Z"},
{"id": "83645", "data": "eth", "timestamp": "2017-10-17T01:32:25.640Z"},
{"id": "36153", "data": "her", "timestamp": "2017-10-17T01:56:13.478Z"},
{"id": "31383", "data": "sry", "timestamp": "2017-10-17T05:56:56.362Z"},
{"id": "68123", "data": "rya", "timestamp": "2017-10-17T06:34:30.652Z"}]
var t, h, n, obj = {};
for(var i=0; i<a.length; i++) {
t = new Date(a[i].timestamp);
if ( !isNaN( t.getTime() ) ) { //if date is valid
h = t.getHours();
n = h + ':00-' + h + ':59';
if(typeof obj[n] === 'undefined') obj[n] = [];
obj[n].push(a[i]);
}
}
console.log(obj);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Multilinear generalization of Cauchy-Schwarz inequality
Let $V$ be a real vector space, and let $(\cdot,\cdot;\cdot,\cdot) : V^4 \to \mathbb{R}$ be a multilinear form with the following properties:
$(x,y;z,w) = (y,x;z,w) = (x,y;w,z)$ (symmetry in the first and second pairs)
$(x,x;z,z) \ge 0$ (positive semidefiniteness in the first and second pairs).
Must such a form satisfy the inequality $$|(x,y;z,w)| \le \sqrt{(x,x;z,z)(y,y;w,w)}?$$
The prototype I have in mind is something like $V = C_c^\infty(\mathbb{R}^n)$, with
$$(f,g;h,k) = \int f g \nabla h \cdot \nabla k$$
in which case the inequality follows by using Cauchy-Schwarz twice (first in $\mathbb{R}^n$, and then in $L^2(\mathbb{R}^n)$).
I'd settle for the inequality
$$|(x,y;z,w)| \le C({\epsilon}(x,x;z,z) + \epsilon^{-1}(y,y;w,w))$$
which follows from the above by AM-GM (with $C = 1/2$). I'd also settle for the special case $x=w, y=z$ where it reads $|(x,z;x,z)| \le \sqrt{(x,x;z,z)(z,z;x,x)}$.
Simply using Cauchy-Schwarz in each pair gives the inequality
$$|(x,y;z,w)| \le [(x,x;z,z)(x,x;w,w)(y,y;z,z)(y,y;w,w)]^{1/4}$$ which has cross terms that I don't want. Edit: Of course, as Willie Wong points out and zeb's counterexample confirms, this doesn't work.
Thanks!
A:
Even the inequality $(x,z;x,z)^2 \le (x,x;z,z)(z,z;x,x)$ is false:
Let $V = \mathbb{R}^2$, with basis $x,z$. Take $(x,x;x,x) = 100$, $(x,z;x,x)=0$, $(z,z;x,x)=1$, $(x,x;x,z)=0$, $(x,z;x,z)=50$, $(z,z;x,z)=0$, $(x,x;z,z) = 1$, $(x,z;z,z)=0$, $(z,z;z,z)=100$, and extend to all of $V^4$ by symmetry and multilinearity.
To check that positive semi-definiteness holds, note that we just need to check that
$(x+az,x+az;x+bz,x+bz) = 100 + a^2 + 200ab + b^2 + 100a^2b^2 \ge 0$,
which easily follows from AM-GM.
Now note that we have $2500 = (x,z;x,z)^2 > (x,x;z,z)(z,z;x,x) = 1$.
In fact, we even have $6250000 = (x,z;x,z)^4 > (x,x;x,x)(x,x;z,z)(z,z;x,x)(z,z;z,z) = 10000$.
Edit: On the other hand, we can prove the following inequality:
$4(x,y;z,w)^2 \le ((x,x;z,z)+(x,x;w,w))((y,y;z,z)+(y,y;w,w))$.
To see this, note that by positive semi-definiteness we have
$0 \le (x+ay,x+ay;z+w,z+w) + (x-ay,x-ay;z-w,z-w)$
$ = 2((x,x;z,z)+(x,x;w,w)) + 8a(x,y;z,w) + 2a^2((y,y;z,z)+(y,y;w,w))$
for any $a$, and plugging in $a = -\frac{2(x,y;z,w)}{(y,y;z,z)+(y,y;w,w)}$ we get the desired inequality.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can BufferedInputStream.read(byte[] b, int off, int len) ever return 0? Are there significant, broken InputStreams that might cause this?
Is it ever possible for BufferedInputStream(byte[] b, int off, int len) to return 0?
READER'S DIGEST VERSION (you can read the rest below, for context, but I think it boils down to this:) Are there InputStreams (i.e. SocketInputStream, CipherInputStream, etc. in the JDK or in commonly used libraries (i.e. Apache Commons, Guava), that don't correctly honor the contract of InputStream.read(byte[],off,len) and might return '0' even if len != 0?
(Note 1: my interest is whether it can really happen in code that uses just the JDK, or maybe a few really common Java libraries, such as Apache Commons; I am looking at the javadoc for clue, but I am also looking at the source for BufferedInputStream (Java 7, in case it matters) in case some edge case is not documented correctly -- and I'm not fully convinced one way or another, thus my question)
(Note 2: I don't mean in the trivial case, where len==0, I mean in the general case, where you pass in a non-zero array, can you ever get back 0 bytes?)
The javadoc is here and it says, in part:
This method implements the general contract of the *corresponding* [my emphasis added] read method of the InputStream class. As an additional convenience, it attempts to read as many bytes as possible by repeatedly invoking the read method of the underlying stream. This iterated read continues until one of the following conditions becomes true:
[two irrelevant conditions omitted]
- The available method of the underlying stream returns zero, indicating that further input requests would block.
And then the doc for the return value says:
Returns: the number of bytes read, or -1 if the end of the stream has been reached.
So: by my reading of this, it's possible that when you call this read function, if no data is buffered and no data is available from the underlying InputStream (say, from a stalled http transfer,) then the read method should return 0, since 0 bytes were read.
and yet… a bunch of folks who seem to know more about this than me seem to believe that this read method will always return EOF or at least one byte.
So, I looked further into InputStream, to see what the general contract of the corresponding read method of the InputStream class really means, and I found this:
If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.
So, according to the javadocs, I think this means BufferedInputStream should not return a 0. If I were looking only at the docs, I think I would be done now.
But: upon inspection, it seems to me that the implementation of BufferedInputStream doesn't really guarantee one byte or more bytes; it inherits this guarantee by depending on correct behavior of the underlying InputStream. The source for the abstract InputStream seems to get this guarantee correct (I think it can only return 0 bytes if len==0) but I don't know if this is true for all input streams in the JDK, let alone all input streams anywhere.
So. I think where I am so far is: BufferedInputStream will never return 0 unless the wrapped InputStream doesn't honor this guarantee of 1 or more bytes -- but I don't know how common this is.
1) Is my general analysis correct?
2) does anybody know of significant cases where InputStreams can return 0? (i.e. InputStreams that may return 0 with a non-zero len, so that if you wrap them in a BufferedInputStream, you need to guard against a zero return value? -- not somebody's personal, broken code, but important cases to watch out for, say in the JDK or Apache Commons or something.)
Apologies for the long question; I was doing more research as I wrote this, so the question grew.
NOTE: for context: I'm posting this question because I didn't understand a conversation I had in reference to this other question (Socket reading using BufferedInputStream) -- it might help to read that question for background.
A:
You didn’t read the spec of BufferedInputStream carefully enough. You cited:
This iterated read continues until one of the following conditions becomes true:
[two irrelevant conditions omitted]
The available method of the underlying stream returns zero, indicating that further input requests would block.
The BufferedInputStream will fulfill the contract of read reading at least one byte by directly delegating to the underlying stream for the first read. If the underlying stream correctly reads at least one byte for that first read, the contract has been fulfilled.
Only subsequent read attempts (the “iterated read”) are conditional, i.e. will be skipped if available returns 0 telling that another read attempt would block (again).
So the bottom line is that BufferedInputStream fulfills the contract, like all other JDK’s InputStreams — as far as I know. By the way, if you want to read an array entirely you can wrap the stream in a DataInputStream which offers a readFully method.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find the closest month-day to a date, no matter the year
I have the following vector of dates (length = 51863)
dates_sim <- seq(from=as.Date("1871-01-01", format = "%Y%m%d"), to=as.Date("2012-12-31", format = "%Y%m%d"), by="days")
And a data frame of dates, with 125 rows and 51863 columns. For each date of my vector, I have 125 corresponding dates in my data frame.
I'll take an example with only one date:
For the date "1871-01-01" I have these corresponding dates:
[1] "2007-12-23" "1964-01-01" "1995-01-03" "1997-02-01" "1993-03-28" "1978-01-21" "1986-12-10" "1982-02-20" "1993-11-16" "1973-12-10" "1964-11-30" "1997-10-29"
[13] "1999-03-15" "1993-01-02" "1993-02-25" "1985-02-19" "2006-03-13" "1976-03-10" "1976-11-15" "1986-03-11" "1975-02-23" "1962-01-31" "1959-11-08" "1979-02-18"
[25] "2003-02-08" "1983-12-13" "2006-03-13" "1984-02-16" "1997-02-01" "1976-03-20" "2000-01-12" "1976-11-15" "1968-12-12" "1979-02-18" "1976-03-10" "1975-01-02"
[37] "1998-11-23" "1979-01-15" "1991-01-28" "1986-12-10" "1959-11-08" "1966-01-06" "1970-12-16" "1995-01-05" "1959-03-13" "1966-03-05" "1971-03-01" "1975-02-22"
[49] "1962-01-30" "1958-11-12" "1964-01-01" "2000-01-10" "1982-02-24" "2003-02-11" "1993-02-24" "1962-01-30" "1976-03-20" "1989-01-20" "1975-01-02" "2002-12-03"
[61] "2003-02-08" "1993-01-01" "1973-12-10" "1998-12-08" "1993-03-28" "1994-12-24" "1983-12-13" "1964-01-18" "1987-01-18" "1959-02-09" "1998-11-24" "1983-12-07"
[73] "2006-03-13" "1972-12-20" "2007-12-23" "1984-02-17" "1959-03-13" "1964-01-01" "1985-03-08" "1973-01-01" "2003-12-31" "1994-12-24" "1972-01-18" "1995-01-14"
[85] "1998-12-07" "1966-03-05" "2007-11-17" "1983-12-07" "1986-03-13" "1964-01-18" "1972-02-28" "1992-02-26" "1992-12-31" "1976-03-10" "1974-11-06" "1995-01-05"
[97] "2003-02-08" "1979-02-18" "1969-12-19" "1969-12-13" "1959-02-09" "1976-03-20" "1986-03-11" "1998-11-22" "1982-02-20" "1969-12-20" "1966-01-09" "1979-02-19"
[109] "1981-02-25" "1984-02-18" "1982-02-19" "1966-01-05" "1987-01-18" "1991-11-24" "1998-01-21" "1983-03-02" "1979-02-18" "1984-01-10" "1984-02-17" "1962-01-31"
[121] "2002-11-05" "1974-03-06" "1971-03-01" "2002-01-14" "2000-01-11"
Among these 125 dates, I want to find the 20 dates which are the closest to "1871-01-01" no matter what the year is. So in fact I just want to find the 20 dates where "month-day" is the closest to "01-01".
For that, I transformed the dates to "day oh the year" so my 125 corresponding dates became:
[1] "357" "001" "003" "032" "087" "021" "344" "051" "320" "344" "335" "302" "074" "002" "056" "050" "072" "070" "320" "070" "054" "031" "312" "049" "039" "347"
[27] "072" "047" "032" "080" "012" "320" "347" "049" "070" "002" "327" "015" "028" "344" "312" "006" "350" "005" "072" "064" "060" "053" "030" "316" "001" "010"
[53] "055" "042" "055" "030" "080" "020" "002" "337" "039" "001" "344" "342" "087" "358" "347" "018" "018" "040" "328" "341" "072" "355" "357" "048" "072" "001"
[79] "067" "001" "365" "358" "018" "014" "341" "064" "321" "341" "072" "018" "059" "057" "366" "070" "310" "005" "039" "049" "353" "347" "040" "080" "070" "326"
[105] "051" "354" "009" "050" "056" "049" "050" "005" "018" "328" "021" "061" "049" "010" "048" "031" "309" "065" "060" "014" "011"
And I can look at the difference between this vector and number 01 (for 01-01). The problem is that, for the day 12-31 I get the number "365" and when I do the difference I have "364" whereas the "12-31" is one of the closest dates to "01-01".
How can I do to look for the 20 closest dates to "01-01", and taking into account that december is one of the closest month to january and july is the further?
A:
Let's say that x is your "target date" and y is your vector of dates from which you want to find the closest one to x, with your definition of "close". I'd suggest something like this:
daysDiff<-abs(as.POSIXlt(x)$yday-as.POSIXlt(y)$yday)
which.min(pmin(daysDiff,365-daysDiff))
Of course this will not take into account leap years.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to save attachments from MS Access 2007 using Java?
I have table in Access where i store id my task and attachment (docx file) to it. Attachment has datatype "Attachment". I need to save this attachment to diskspace using java(each file in own directory). When i export this table to XML i see some like this
<Findings>
<id>265</id>
<Finding>
<FileData>FgAAAAEAAAAFAAAAZABvAGMAeAAAAFBLAwQUAAYACAAAACEACSSHgoEBAACOBQAA
Ew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Name>
<FileType>docx</FileType>
</Finding>
<IDfind>PAY-14 1 07 01r7</IDfind>
</Findings>
with XML tags. Then I using DOM parser parse this XML and save to File(with extension docx) each FileData. But Word show error when i try to open this file. Can you help me solve my problem?
Here is my java code
File xmlFile = new File(filepath);
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
NodeList list = doc.getElementsByTagName("Findings");
int length = list.getLength();
Node nNode = null;
for (int temp = 0; temp < length; temp++) {
nNode = list.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String ids = eElement.getElementsByTagName("id").item(0)
.getTextContent();
Node finding = eElement.getElementsByTagName("Finding")
.item(0);
if (finding != null
&& finding.getNodeType() == Node.ELEMENT_NODE) {
Element find = (Element) finding;
String findName = find.getElementsByTagName("FileName")
.item(0).getTextContent();
String data = find.getElementsByTagName("FileData")
.item(0).getTextContent();
String decdata = StringUtils.newStringUtf8(Base64
.decodeBase64(data));
String todec = decdata.substring(decdata.indexOf("PK"));
String[] id = ids.split(" ");
if (id.length > 1) {
for (int idf = 0; idf < id.length; idf++) {
int idfind = Integer.parseInt(id[idf]);
File tempf = new File(defaultFileDirectory
+ idfind + "\\" + findName);
FileUtils.writeStringToFile(tempf, todec,
"UTF8");
}
} else {
int idf = Integer.parseInt(ids);
File tempf = new File(defaultFileDirectory + idf
+ "\\" + findName);
FileUtils.writeStringToFile(tempf, decdata, "UTF8");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
A:
It is common for binary data to be Base64 encoded when included in an XML file. I took the <FileData> from your example, Base64 decoded it, and then wrote it to a file. The result was this:
That looks like a .docx file with 22 bytes of "junk" at the very beginning. (A .docx file is actually a ZIP archive, so the first two bytes of the file should be 'PK', or 0x50 0x4B.)
I was able to successfully create the Word document by:
extracting the <FileData> text,
Base64 decoding it,
stripping off the leading bytes that precede 'PK' (0x50 0x4B), and
saving the rest as a .docx file.
Implementation example: Once you have the <FileData> text extracted to a String variable named strEncoded you could extract the .docx file using code like this:
byte[] bytesDecoded = DatatypeConverter.parseBase64Binary(strEncoded);
int pkStart = -1;
for (int i = 0; i < (bytesDecoded.length - 1); i++) {
if (bytesDecoded[i] == 0x50) { // "P"
if (bytesDecoded[i+1] == 0x4B) { // "K"
pkStart = i;
break;
}
}
}
if (pkStart < 0) {
System.out.println("Did not find 'PK' marker in decoded data.");
}
else {
FileOutputStream fos = new FileOutputStream("C:\\Users\\Gord\\Desktop\\Hello.docx");
fos.write(Arrays.copyOfRange(bytesDecoded, pkStart, bytesDecoded.length));
fos.close();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should We Zap The Low-Occurrence Tags?
I just looked on SO, and found that there are about 12,880 tags with only a single use. There are 26,250 used less than 10 times.
That's just too many for the community to fix. I think we need some automatic cleanup here.
I suggest you add a cleanup process to remove all tags used less than a certain number of times more than a month after their creation. That would give a legitimate tag a while to become used more, while removing those that will never be used more than a few times.
Edit: Here are the tags from page 512. I've highlighted the ones I think are most likely bad tags. I even fixed a few:
installer-class
inspector
installation-tools
insert-worksheet
insets
insomnia-mysteries
inorder
inprivate
inprocfactory
inprocserver
in-progress
input-button
input-buffer
input-mask
inputformsection
insert-nested-select
insert-parameters
insert-img-to-option
insert-data
insertdate
insert-delayed
insertafter
insertchildbefore
input-mode
input-simulation
inputpanel
inputrc
input-redirection
inquiry-management
inputstreamreader
input-string
input-testing
infocards
infochannel
infogrid
inflector
influence
info-plist
inforeader
inform
inform7
information-base
information-card
information-dispersal
informed-search
information-sources
information-technology
information-ownership
information-science
info-vis
informx (fixed now)
info-window
infralution
inheritence (typo - fixed)
initialcapacity
initial-context
initialization-block
initfileurlwithpath
inline-comments
inline-cpp
inline-edit
inlinec
initialize-request-handl
injectable
injectors
init-script
inittab
initwithcontentsoffile
initwithcontentsofurl
inlinks
A:
I don't know -- can anyone make a case for these single use tags existing for more than a month?
edit: I am convinced this is a useful cleanup task, to remove these orphaned tags from the system automatically. I've implemented a routine that removes tags created more than 6 months ago (12 months on Meta sites) which have been used only a single time. It will run monthly.
Right now I am running it by hand over the tiers and I got these stats so far:
Stack Overflow, ~7,400 tags removed (/tags went from 522 pages to 415 pages)
Super User, 866 tags removed http://pastebin.com/HBRaFsfm
Server Fault, 1224 tags removed http://pastebin.com/jauyQv5k
Meta (prod), 474 tags removed http://pastebin.com/nT8h6bTj
(note: where you see multiple posts being updated, it's because there are "extra" deleted posts with that tag.)
I spot checked a whole bunch of them, and removal seemed correct to me in every instance. It's almost always a case of over-tagging, where the question asker sprayed 1 or 2 "extra" tags on the question of extremely low value, when the more general tags they also included were perfectly adequate.
There is some code at the end to deal with questions which end up with ZERO tags after removal of the one-use orphan tags -- it tags these untagged. But that is exceedingly rare.
Any tags not currently in use, or that happen to get orphaned through unusual means (rollback, merge, etc), are removed every 24 hours by a background process.
A:
I really dislike the idea of automatically deleting perfectly legitimate tags just because they are not used frequently. If someone tags a question about the "xyzzy" programming language with the tag "xyzzy", then it seems rude to delete it even if there are only a couple of instances. You would basically be telling people with questions about rare or unusual technologies not to bother to come here.
A:
I think the problem is likely to continue to get worse, as it arises from a simple fact: it is MUCH easier to introduce a new tag than it is to find existing ones that are suitable. Worse, the asymmetry in effort becomes more and more pronounced as the growing number of low use tags dilute the good ones. The frequent need to merge tags that are straightforward aliases of each other is proof of this (vs2010/visual-studio-2010, subversion/svn, mercurial/hg, etc.)
Ideally, it would be best if it required more effort on the part of the user to introduce a new tag than it takes to select ones that already exists.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Filter dataset for duration of time since first observation R
How would I go about filtering a dataset to remove all observations above a specific duration and any grouped observations (focal_id) below a specific threshold? My question is similar in principle to this OP.
Here is a sample of the dataset:
focal_id time first_time
1 9128 08:40:30 08:40:30
2 9128 08:40:57 08:40:30
3 9128 08:41:27 08:40:30
4 9128 08:41:57 08:40:30
5 9128 08:42:27 08:40:30
6 9128 08:42:57 08:40:30
7 9128 08:43:27 08:40:30
8 9128 08:43:57 08:40:30
9 9128 08:44:17 08:40:30
10 9128 08:44:29 08:40:30
11 9128 08:44:29 08:40:30
12 9128 08:45:06 08:40:30
13 9128 08:45:28 08:40:30
14 9128 08:46:32 08:40:30
15 9128 08:46:58 08:40:30
16 9128 08:47:28 08:40:30
17 9128 08:47:28 08:40:30
18 9128 08:48:00 08:40:30
19 9128 08:48:30 08:40:30
20 9128 08:48:31 08:40:30
21 1022 06:20:02 06:20:02
22 1022 06:20:32 06:20:02
23 1022 06:21:00 06:20:02
24 1022 06:21:34 06:20:02
In this above example, I would want to filter out any observations (i.e., rows) after 7 minutes and 15 seconds (from the first time) and any focal_id with less than 5 minutes and 30 seconds of observations (i.e., rows) from the first time.
As a first step, I use dplyr to do the following:
filter_dataset<-dataset %>%
group_by(focal_id) %>%
arrange(time) %>%
mutate(first_time=min(time))
There has to be a way to calculate the duration (which I can then use to filter focal_id with < 5m30s minutes of observations) and also filter observations > 7m15s minutes for focal_id with durations that are longer than 7 minutes and 15 seconds.
I tried working within the lubridate package by first setting my time to hms, but this returned only the seconds. I also tried the duration function in the lubridate package, but it returned NAs.
This is my desired final output:
focal_id time duration
1 9128 08:40:30 00:06:58
2 9128 08:40:57 00:06:58
3 9128 08:41:27 00:06:58
4 9128 08:41:57 00:06:58
5 9128 08:42:27 00:06:58
6 9128 08:42:57 00:06:58
7 9128 08:43:27 00:06:58
8 9128 08:43:57 00:06:58
9 9128 08:44:17 00:06:58
10 9128 08:44:29 00:06:58
11 9128 08:44:29 00:06:58
12 9128 08:45:06 00:06:58
13 9128 08:45:28 00:06:58
14 9128 08:46:32 00:06:58
15 9128 08:46:58 00:06:58
16 9128 08:47:28 00:06:58
17 9128 08:47:28 00:06:58
A:
In the code below, if you want to keep duration as a duration (rather than a time) then remove the as_hms().
library(tidyverse)
library(hms)
dataframe %>%
mutate(time=as_hms(time),
first_time=as_hms(first_time)) %>%
filter(time - first_time < 7.25*60) %>%
group_by(focal_id) %>%
mutate(duration = as_hms(max(time - first_time))) %>%
filter(duration > 5.5*60)
focal_id time first_time duration
<int> <time> <time> <time>
1 9128 08:40:30 08:40:30 06'58"
2 9128 08:40:57 08:40:30 06'58"
3 9128 08:41:27 08:40:30 06'58"
4 9128 08:41:57 08:40:30 06'58"
5 9128 08:42:27 08:40:30 06'58"
6 9128 08:42:57 08:40:30 06'58"
7 9128 08:43:27 08:40:30 06'58"
8 9128 08:43:57 08:40:30 06'58"
9 9128 08:44:17 08:40:30 06'58"
10 9128 08:44:29 08:40:30 06'58"
11 9128 08:44:29 08:40:30 06'58"
12 9128 08:45:06 08:40:30 06'58"
13 9128 08:45:28 08:40:30 06'58"
14 9128 08:46:32 08:40:30 06'58"
15 9128 08:46:58 08:40:30 06'58"
16 9128 08:47:28 08:40:30 06'58"
17 9128 08:47:28 08:40:30 06'58"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to hook up a COM event dispatcher?
The VBIDE API exposes the wonderfully cryptic _dispVBComponentsEvents interface (among others), which look like something that I could use to capture various interesting events in the VBE.
So I implemented the interface in a class that intends to capture the event and raise a "normal" .net event for the rest of my application to handle, like this:
public class VBComponentsEventDispatcher : _dispVBComponentsEvents
{
public event EventHandler<DispatcherEventArgs<VBComponent>> ComponentAdded;
public void ItemAdded(VBComponent VBComponent)
{
OnDispatch(ComponentAdded, VBComponent);
}
public event EventHandler<DispatcherEventArgs<VBComponent>> ComponentRemoved;
public void ItemRemoved(VBComponent VBComponent)
{
OnDispatch(ComponentRemoved, VBComponent);
}
public event EventHandler<DispatcherRenamedEventArgs<VBComponent>> ComponentRenamed;
public void ItemRenamed(VBComponent VBComponent, string OldName)
{
var handler = ComponentRenamed;
if (handler != null)
{
handler.Invoke(this, new DispatcherRenamedEventArgs<VBComponent>(VBComponent, OldName));
}
}
public event EventHandler<DispatcherEventArgs<VBComponent>> ComponentSelected;
public void ItemSelected(VBComponent VBComponent)
{
OnDispatch(ComponentSelected, VBComponent);
}
public event EventHandler<DispatcherEventArgs<VBComponent>> ComponentActivated;
public void ItemActivated(VBComponent VBComponent)
{
OnDispatch(ComponentActivated, VBComponent);
}
public event EventHandler<DispatcherEventArgs<VBComponent>> ComponentReloaded;
public void ItemReloaded(VBComponent VBComponent)
{
OnDispatch(ComponentReloaded, VBComponent);
}
private void OnDispatch(EventHandler<DispatcherEventArgs<VBComponent>> dispatched, VBComponent component)
{
var handler = dispatched;
if (handler != null)
{
handler.Invoke(this, new DispatcherEventArgs<VBComponent>(component));
}
}
}
I'm hoping to use the class like this:
var componentsEvents = new VBComponentsEventDispatcher();
componentsEvents.ComponentAdded += componentsEvents_ComponentAdded;
componentsEvents.ComponentActivated += componentsEvents_ComponentActivated;
//...
void componentsEvents_ComponentAdded(object sender, DispatcherEventArgs<VBComponent> e)
{
Debug.WriteLine(string.Format("Component '{0}' was added.", e.Item.Name));
}
void componentsEvents_ComponentActivated(object sender, DispatcherEventArgs<VBComponent> e)
{
Debug.WriteLine(string.Format("Component '{0}' was activated.", e.Item.Name));
}
But it doesn't work, I get no debug output and a breakpoint isn't hit. Clearly I don't know what I'm doing. MSDN is completely useless on the subject, and finding documentation about this is harder than finding the maiden name of the third wife of Henry VIII.
What am I doing wrong, and how do I get this to work? Am I on the right track?
A:
Am I on the right track?
Yes. What you have in an event sink - you're missing a bit of code to register the sink with the COM servers.
The VBProjects and VBComponents interfaces implement (somewhere very deep) the IConnectionPointContainer interface - you need to use that to collect IConnectionPoint instances. And to un-register the sink, you'll need a data structure to remember the int cookie that the registration step gives you.
Here's a rough example - say you have an App class with these fields:
private readonly IConnectionPoint _projectsEventsConnectionPoint;
private readonly int _projectsEventsCookie;
private readonly IDictionary<VBComponents, Tuple<IConnectionPoint, int>> _componentsEventsConnectionPoints =
new Dictionary<VBComponents, Tuple<IConnectionPoint, int>>();
Somewhere in the constructor, you'll register the sink using IConnectionPoint.Advise, and register your custom event handlers:
var sink = new VBProjectsEventsSink();
var connectionPointContainer = (IConnectionPointContainer)_vbe.VBProjects;
Guid interfaceId = typeof (_dispVBProjectsEvents).GUID;
connectionPointContainer.FindConnectionPoint(ref interfaceId, out _projectsEventsConnectionPoint);
sink.ProjectAdded += sink_ProjectAdded;
sink.ProjectRemoved += sink_ProjectRemoved;
sink.ProjectActivated += sink_ProjectActivated;
sink.ProjectRenamed += sink_ProjectRenamed;
_projectsEventsConnectionPoint.Advise(sink, out _projectsEventsCookie);
Then, when a project is added, you'll register a sink for each component using IConnectionPoint.Advise, then you can register your custom event handlers, and add an entry to your dictionary:
void sink_ProjectAdded(object sender, DispatcherEventArgs<VBProject> e)
{
var connectionPointContainer = (IConnectionPointContainer)e.Item.VBComponents;
Guid interfaceId = typeof(_dispVBComponentsEvents).GUID;
IConnectionPoint connectionPoint;
connectionPointContainer.FindConnectionPoint(ref interfaceId, out connectionPoint);
var sink = new VBComponentsEventsSink();
sink.ComponentActivated += sink_ComponentActivated;
sink.ComponentAdded += sink_ComponentAdded;
sink.ComponentReloaded += sink_ComponentReloaded;
sink.ComponentRemoved += sink_ComponentRemoved;
sink.ComponentRenamed += sink_ComponentRenamed;
sink.ComponentSelected += sink_ComponentSelected;
int cookie;
connectionPoint.Advise(sink, out cookie);
_componentsEventsConnectionPoints.Add(e.Item.VBComponents, Tuple.Create(connectionPoint, cookie));
}
When a project is removed, you un-register the sinks using IConnectionPoint.Unadvise, and remove the dictionary entry:
void sink_ProjectRemoved(object sender, DispatcherEventArgs<VBProject> e)
{
Tuple<IConnectionPoint, int> value;
if (_componentsEventsConnectionPoints.TryGetValue(e.Item.VBComponents, out value))
{
value.Item1.Unadvise(value.Item2);
_componentsEventsConnectionPoints.Remove(e.Item.VBComponents);
}
}
And then you can run any code you want in your handler:
void sink_ComponentAdded(object sender, DispatcherEventArgs<VBComponent> e)
{
_parser.State.OnParseRequested(e.Item);
}
If you have a Dispose method in your App class, that would be a good place to clean up any remnants:
public void Dispose()
{
_projectsEventsConnectionPoint.Unadvise(_projectsEventsCookie);
foreach (var item in _componentsEventsConnectionPoints)
{
item.Value.Item1.Unadvise(item.Value.Item2);
}
}
A:
The System.Runtime.InteropServices namespace exposes a static ComEventsHelper class to connect managed delegates to unmanaged dispatch sources. This basically does the same thing as the other answer, but the connection points are handled within the runtime callable wrapper instead of having to be managed explicitly from the calling code (thus making it somewhat more robust). I suspect that this is how PIAs are handling source interfaces internally (decompiling the Microsoft.Vbe.Interop in question mangled it enough that it's hard to tell).
In this case, for some unfathomable reason the interface in question isn't declared as a source interface, so the PIA build didn't connect the event handlers in the runtime wrapper. So... you can wire up the handlers manually in the wrapper class and forward them as wrapped events, but still leave the heavy lifting (and thread safety management) of dealing with the connection points to the RCW. Note that you need 2 pieces of information from the referenced type library - the guid of the _dispVBComponentsEvents interface and the DispId's of the unmanaged events that you're interested in listening to:
private static readonly Guid VBComponentsEventsGuid = new Guid("0002E116-0000-0000-C000-000000000046");
private enum ComponentEventDispId
{
ItemAdded = 1,
ItemRemoved = 2,
ItemRenamed = 3,
ItemSelected = 4,
ItemActivated = 5,
ItemReloaded = 6
}
Then, wire them up in the ctor of the class wrapper (only one shown for the sake of brevity)...
private delegate void ItemAddedDelegate(VB.VBComponent vbComponent);
private readonly ItemAddedDelegate _componentAdded;
public VBComponents(VB.VBComponents target)
{
_target = target;
_componentAdded = OnComponentAdded;
ComEventsHelper.Combine(_target,
VBComponentsEventsGuid,
(int)ComponentEventDispId.ItemAdded,
_componentAdded);
}
...and forward the events:
public event EventHandler<DispatcherEventArgs<IVBComponent>> ComponentAdded;
private void OnComponentAdded(VB.VBComponent vbComponent)
{
OnDispatch(ComponentAdded, VBComponent);
}
private void OnDispatch(EventHandler<DispatcherEventArgs<IVBComponent>> dispatched, VB.VBComponent component)
{
var handler = dispatched;
if (handler != null)
{
handler.Invoke(this, new DispatcherEventArgs<IVBComponent>(new VBComponent(component)));
}
}
When you're done, un-register the delegate by calling ComEventsHelper.Remove:
ComEventsHelper.Remove(_target,
VBComponentsEventsGuid,
(int)ComponentEventDispId.ItemAdded,
_componentAdded);
The example above uses a wrapper class per the question, but the same method could be used from anywhere if you need to attach additional functionality to a COM event before handling it or passing it on to other listeners.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to parse a value inside json object in javascript
I am trying to parse a value which is residing inside a json object . Below is the response from my API call.
var responseData = {
"statusCode": 200,
"body": "{\"Errors\":\"\",\"Message\":null,\"OrgID\":0,\"Output\":\"{\\\"AllUserDetails\\\":{\\\"UserDetails \\\":[{\\\"UserID\\\":1012,\\\"UserName\\\":\\\"Arul, Velu\\\",\\\"EmpID\\\":null,\\\"Role\\\":\\\"SA\\\",\\\"RoleName\\\":\\\"Super Admin\\\",\\\"EmailID\\\":\\\"Arulvelu@gmail.com\\\",\\\"NT_UID\\\":\\\"ICS\\\\\\\\RNair\\\",\\\"Frm_UID\\\":\\\"Arulvelu@gmail.com\\\",\\\"Frm_PWD\\\":\\\"3ZD1KS+4gEL5RKsjlC5k0MIfaiV8k\\/ixZRS6NpNyu0g=\\\",\\\"Org_Id\\\":1,\\\"Instance_Model\\\":\\\"Dependent\\\",\\\"Org_Name\\\":\\\"India\\\",\\\"AccessCreate_Portfolio\\\":false,\\\"AccessEdit_Portfolio\\\":false,\\\"Customer\\\":2592,\\\"Customer_Name\\\":\\\"ICS\\\",\\\"Location\\\":null,\\\"Location_Name\\\":\\\"\\\",\\\"Userlevel\\\":2544,\\\"User_Level\\\":\\\"Analyst\\\",\\\"Country\\\":null,\\\"Designation\\\":\\\"Consultant\\\",\\\"ContactNo\\\":\\\"2133232123\\\",\\\"MobileNo\\\":null,\\\"JoinDate\\\":\\\"2016-01-06 00:00:00\\\",\\\"Access_ServerMon\\\":false,\\\"Access_IncidentMgmt\\\":true,\\\"Access_CMCMDB\\\":true,\\\"Access_CMDB\\\":true,\\\"Access_RM\\\":true,\\\"Access_KnowledgeMgmt\\\":true,\\\"Access_PortfolioMgmt\\\":true,\\\"Access_ServiceRequest\\\":true,\\\"Access_ServiceCatalog\\\":true,\\\"Access_NetworkMon\\\":false,\\\"Access_AssetMgmt\\\":true,\\\"Access_ProblemMgmt\\\":true,\\\"Access_ProjectMgmt\\\":true,\\\"Access_SkillPack\\\":true,\\\"Access_FinMgmt\\\":false,\\\"Access_SLA\\\":true,\\\"SLAMgr\\\":false,\\\"AccessType_ServerMon\\\":\\\"No Access\\\",\\\"AccessType_IncidentMgmt\\\":\\\"No Access\\\",\\\"AccessType_CMCMDB\\\":\\\"No Access\\\",\\\"AccessType_CMDB\\\":\\\"\\\",\\\"AccessType_RM\\\":\\\"\\\",\\\"AccessType_KnowledgeMgmt\\\":\\\"\\\",\\\"AccessType_PortfolioMgmt\\\":\\\"\\\",\\\"AccessType_ServiceRequest\\\":\\\"\\\",\\\"AccessType_ServiceCatalog\\\":\\\"\\\",\\\"AccessType_NetworkMon\\\":\\\"No Access\\\",\\\"AccessType_AssetMgmt\\\":\\\"No Access\\\",\\\"AccessType_ProblemMgmt\\\":\\\"No Access\\\",\\\"AccessType_ProjectMgmt\\\":\\\"No Access\\\",\\\"AccessType_SkillPack\\\":\\\"No Access\\\",\\\"AccessType_WorkOrder\\\":\\\"No Access\\\",\\\"AccessType_FinMgmt\\\":\\\"No Access\\\",\\\"AccessType_SLA\\\":\\\"\\\",\\\"Address\\\":\\\"2901 Butterfield Rd\\\\n2nd Flooor\\\",\\\"UserRemarks\\\":\\\"\\\",\\\"State\\\":\\\"\\\",\\\"City\\\":\\\"\\\",\\\"Pin\\\":\\\"\\\",\\\"Active\\\":true,\\\"UT_ID\\\":90,\\\"AccessType_SkillPack1\\\":\\\"No Access\\\",\\\"Access_EProc\\\":true,\\\"AccessType_Eproc\\\":\\\"General Access\\\",\\\"Entity_Access\\\":\\\"\\\",\\\"TimeZone\\\":\\\"(UTC - 06:00) CST - Central Standard Time\\\",\\\"GMT_TimeDiff\\\":-300,\\\"Access_EventMgmt\\\":false,\\\"AccessType_EventMgmt\\\":\\\"No Access\\\",\\\"Keyword_Access\\\":\\\"\\\",\\\"ManagerName\\\":\\\"Arulvelu\\\",\\\"ProjMgmt_InstanceAccess\\\":\\\"\\\",\\\"Manager_UserID\\\":null,\\\"IM_ExtendedRole\\\":\\\"RPT\\\",\\\"AM_ExtendedRole\\\":\\\"RPT\\\",\\\"CustomerMasterID\\\":11,\\\"OrgLogoActive\\\":null,\\\"CustomerLogoActive\\\":null,\\\"AM_EditTemplateID\\\":0,\\\"DesignationID\\\":1381,\\\"PT_userAccessLevel\\\":\\\"Analyst\\\",\\\"PT_workgroupId\\\":0,\\\"PT_CostcentreID\\\":0,\\\"Alternative_EmailID\\\":\\\" , , ,\\\",\\\"ManagerEmailID\\\":null,\\\"ManagerEmployeeID\\\":null}]}}\",\"OutputObject\":null,\"TokenID\":null}",
"headers": {
"cache-control": "private",
"content-type": "application/json; charset=utf-8",
"server": "Microsoft-IIS/8.5",
"set-cookie": [
"ASP.NET_SessionId=2ncl0ezht5; path=/; HttpOnly"
],
"x-aspnet-version": "4.0.30319",
"x-powered-by": "ASP.NET",
"date": "Sat, 13 Oct 2018 20:12:39 GMT",
"connection": "close",
"content-length": "3314"
}
}
I could able to get the body value using responseData.body . But i need to retreive the value which is inside the body.Output.AllUserDetails.UserDetails [0].UserID It throws me an error stating AllUserDetailsis undefined. Can anyone assist me.
A:
Try this:
JSON.parse(JSON.parse(responseData.body).Output).AllUserDetails['UserDetails '][0].UserID
Please note UserDetails has an extra space in api response so you can not access it using the dot notation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why are war atrocities in Yemen reported less often than war atrocities in other conflicts?
UPDATE: Wikileaks just released the Yemen files. Who would have guessed that, the US funded yemeni forces to force the war (once again).
There are many terrible things happening in Yemen, they are being bombed by the Saudi-led coalition. You can see many examples in the Yemen Post Twitter feed. Very many of these, I don't see reported in most mainstream media.
Here is an article on the only decent newspaper out there talking about Yemen.
Why is this?
A:
You're not alone in thinking that the war in the Yemen is under-reported. Medium ranked it as the top underreported stort of 2015 and even the normally reserved BBC described it thus:
...the war in Yemen must rank as one of the most under-reported in recent times, despite a few brave visits by intrepid journalists and film crews
It's always difficult to give a perfect answer to questions like this but we do have some factual sources to go on:
Several journalists and institutes have done research into why the war in Yemen is under-reported and written about this. This includes identifying some specific facts.
Other journalists have written first-hand accounts of limitations in modern reporting, identifying principles and trends, some of which apply to Yemen
Yemen-specific issues
There's a major crackdown on local journalists, including arrests, intimidation, physical violence and more. Here's a quote from Reporters Without Borders director of research Gilles Lourdet, reported in a Pulitzer summary of the problems faced by journalists in Yemen:
Since May 2009 we observed a very bad evolution, with a lot of trials, with a lot of journalists in prison, a lot of journalists harassed and it is really the worst evolution of media freedom in the world
It's extremely difficult for foriegn journalists to get in. As Columbia Journalism Review (CJR) put it in their excellent article Why almost no one’s covering the war in Yemen, which I've quoted from many times and which I recommend reading in full:
...journalists say the current conflagration has made reporting on the country more difficult than at any other time in memory. There are vanishingly few foreign journalists in Yemen as a result of the violence on the ground, access restrictions, and wavering commitment on the part of international news organizations
(we'll come back to the "wavering commitment" part)
At the moment, journalists have no reliable way into Yemen. The Saudi-dominated coalition has bombed the airport in Sanaa, leaving some journalists seeking other routes into the country. Some have attempted to broker passage on ships bringing aid to the country.
For example:
A crew from BBC television managed to enter the southern city of Aden briefly in April, but left soon thereafter, apparently due to security concerns. Other news organizations are covering the conflict from neighboring Saudi Arabia, or from Djibouti, Cairo, or Beirut.
It's hard for those few journalists who are there to get news out. CJR again:
Yemeni journalists, meanwhile, face power outages for days at a time [and] the threat of food shortages
As former Yemen correspondent Adam Baron was quoted in the CJR article:
“It’s the simple fact that it’s literally almost impossible to get information in or out of that country because of the apocalyptic damage and strain to Yemen’s infrastructure.”
General problems in modern journalism that apply to Yemen
But the problem isn't just the difficulty - there's also a lack of will, or as CJR put it:
wavering commitment on the part of international news organizations
Even when journalists have risked everything to get stories out, or when citizens have used social media to tell the world what's happening, many media outlets do almost nothing with these reports.
Why is this? In 2008 experienced journalist Nick Davies published a book describing in detail the ways and reasons why modern newsrooms fail to properly report important stories, Flat Earth News, and some of the principles discussed are relevant to Yemen.
Journalists like "safe" sources. If a journalist publishes a witness account of a Yemeni villager, and it turns out to be a fraud organised by the propaganda division of one of the factions, that journalist feels their reputation is at risk. If a journalist publishes a statement by a Western government which turns out to be equally untrue, they get two stories for the price of one - the original statement, then the subsequent controversy about the misleading statement. So, journalists prefer "official" stories, since they feel their backs are covered, This is a problem for a conflict like Yemen where the actual fighting is done by factions in broad coalitions whose leaders simply don't comment on most incidents, and where finding impartial sources is difficult (CJR again):
the problem of finding sources in a polarized country where violence has hardened attitudes
Modern journalists have little time to do original research or fact-checking, due largely to reduced budgets. This combined with the previous point leads to favouring "he said she said" stories, where they can simply copy a quote from a should-be-reliable source, publish it, and if other should-be-reliable sources dispute it, they quote them in a "controversy over X" piece. In Yemen, Western governments tend to not make statements since it's diplomatically awkward (Saudi Arabia is an ally). Human rights organisations do comment on events in the Yemen, but they are usually met with no response, so this isn't a good way to generate a cheap "he said she said" copy-and-paste controversy.
It's complicated. Modern journalists are pressed for time due to understaffing due to reduced budgets, and favour easy pre-packaged stories that are easy to churn out (a trend dubbed "churnalism" by BBC reporter Waseem Zakir, popularised by Davies' book) over stories where they'll need to take time to properly understand and communicate something complex like the many agendas and loyalties of the many members of the two main military coalitions in the Yemen.
There's no clear easy narrative. Publishers feel stories need a "hook", and for foreign wars this usually means turning it into a "good guys vs bad guys" story where the "good guys" are in some way "like us" or "on our side". For example, the war in Syria was a major story while it could be characterised as the "good" pro-democracy activists and Free Syrian Army vs the "bad" dictator Assad. It then slipped in prominence as many of the anti-Assad forces proved to be even worse than Assad's regime, then roared back into prominence when it could be characterised as the "bad" ISIS vs the "good" Peshmerga and Yarzidi. Neither of the two main military factions in Yemen is easy to characterise as the "good guys", so many news outlets simply don't know how to give the story a hook - and don't try.
Of course, there is a "good guys" faction who should be represented. As Yemeni-Scottish filmmaker Sara Ishaq was quoted in the CJR article:
“We’re trying to represent this third party that isn’t really being represented, and it’s mainly the civilians who are neither pro-Houthi/Saleh nor pro-Saudi.”
...but as previously discussed, modern churnalists don't see ordinary civilians as the kind of source where, if it turns out to be incorrect, the churnalist can cover their backs by turning it into a "he said she said" copy-and-paste controversy. So, they go unrepresented.
A:
It's complicated, but the main reasons is Saudi Money/Allies/Friends & foreign reporters shortage...
One of the reasons is that Saudi media and foreign policy is trying to image the war as if it is a Yemeni-criss not a Saudi led war on Yemen
another reason is that only few foreign journalists are able to report about Yemen because the unsafe situation, in best scenarios they might be hit by an airstrike or be kidnapped by terrorist/AQAP/ISIS groups.
Therefore foreign media either does not talk about it or copies foreign pro Saudi media headlines because Saudi is an ally as @user568458 mentioned.
but to be fair, human organizations do manage to write reports about War on Yemen some times, but even those countable reports about Yemen are either left with no response or condemned by Saudi Arabia.
Despite the dishonesty about war on Yemen although more than 10 months passed so far, the truth will prevail sooner or later, and every one will know about it such as what happened in Vietnam war.
People started talking about Saudi war crimes formally such as this statement in the European parliament which condemned targeting Humanitarian Organization*(which was targeted by Saudi airstrikes)*.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to wrap lists with proper indentation when using org-indent-mode?
In Org-mode I can get headlines wrap with proper indentation by using org-indent-mode. How can I do the same for lists, that is, how can I make it so that lists in Org-mode wrap with proper indentation?
If I insert
* Very very very very very very very very very very very very very very very very very very very long line
- Very very very very very very very very very very very very very very very very very very very long line
into an Org-mode buffer with org-indent-mode I get the following:
* Very very very very very very very very very very very very very very very
very very very very long line
- Very very very very very very very very very very very very very very very
very very very very long line.
Note that the second line of the list (the one starting with -) is not properly indented because it should align with the first letter of the start of the list. What I would expect is the following:
* Very very very very very very very very very very very very very very very
very very very very long line
- Very very very very very very very very very very very very very very very
very very very very long line.
I am running Org-mode 7.6 in GNU Emacs 23.3.1.
A:
This now seems to be the standard in Org-mode version 7.8.03. The news for the release of 7.8 stated that org-ident.el had been refactored for some improvements when used with visual-line-mode (and should be faster).
As a test I ran emacs -q and used Org-mode version 7.7 that comes with emacs24. It showed the undesired behaviour. Adding my local copy of 7.8 to my load-path and reloading org then refreshing the buffer C-c C-c on:
#+STARTUP: indent
added the extra spaces on additonal lines so that indentation matched what you expect.
Upgrading to 7.8.03 (or to current git-head) will provide you with the desired functionality.
Test results
Org-Mode 7.7
#+STARTUP: indent
* Very very very very very very very very very very very
very very very very very very very very long line
- Very very very very very very very very very very very
very very very very very very very very long line.
Org-Mode 7.8.03
#+STARTUP: indent
* Very very very very very very very very very very very
very very very very very very very very long line
- Very very very very very very very very very very very
very very very very very very very very long line.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What are the existing build targets for MSBuild?
MSBuild allows you to specify build-targets such as Build or Clean with -target:<build-target> (Example: MSBuild.exe -target:Clean).
Of course, a developer can define their own target using a .targets xml file.
However, some targets, such as Build or Clean, are pre-defined by Microsoft.
What is the list of all default pre-defined build-targets that are common for all .NET languages?
A:
The standard build-targets that are common for all .NET languages are defined at Microsoft.Common.CurrentVersion.targets.
Here is the full list of build targets:
Build
Rebuild
Clean
Run
Publish
PublishOnly
ResolveReferences
ResolveProjectReferences
ResolveAssemblyReferences
GenerateBindingRedirects
PrepareResources
ResGen
Compile
GenerateManifests
PrepareForRun
CopyFilesToOutputDirectory
CoreBuild
BuildGenerateSources
BuildCompile
BuildLink
CopyRunEnvironmentFiles
BuildOnlySettings
PrepareForBuild
GetFrameworkPaths
GetReferenceAssemblyPaths
AssignLinkMetadata
PreBuildEvent
UnmanagedUnregistration
GetTargetFrameworkVersion
AssignProjectConfiguration
GetTargetPath
GetTargetPathWithTargetPlatformMoniker
GetNativeManifest
ResolveNativeReferences
GenerateBindingRedirects
GenerateBindingRedirectsUpdateAppConfig
ResolveSDKReferences
FindInvalidProjectReferences
ExpandSDKReferences
ExportWindowsMDFile
DesignTimeResolveAssemblyReferences
ResolveComReferences
PrepareResourceNames
AssignTargetPaths
GetItemTargetPaths
SplitResourcesByCulture
CreateCustomManifestResourceNames
ResolveKeySource
GenerateTargetFrameworkMonikerAttribute
GenerateAdditionalSources
GenerateSerializationAssemblies
CreateSatelliteAssemblies
GenerateSatelliteAssemblies
ComputeIntermediateSatelliteAssemblies
SetWin32ManifestProperties
GenerateApplicationManifest
GenerateDeploymentManifest
GetCopyToOutputDirectoryItems
UnmanagedRegistration
IncrementalClean
CleanReferencedProjects
CleanPublishFolder
PostBuildEvent
SetGenerateManifests
PublishBuild
AllProjectOutputGroups
BuiltProjectOutputGroup
DebugSymbolsProjectOutputGroup
DocumentationProjectOutputGroup
SatelliteDllsProjectOutputGroup
SourceFilesProjectOutputGroup
ContentFilesProjectOutputGroup
SGenFilesOutputGroup
GetResolvedSDKReferences
PriFilesOutputGroup
SDKRedistOutputGroup
GetInstalledSDKs
BeforeBuild
AfterBuild
BeforeRebuild
AfterRebuild
BeforeResolveReferences
AfterResolveReferences
BeforeResGen
AfterResGen
BeforeCompile
AfterCompile
BeforeClean
AfterClean
BeforePublish
AfterPublish
The targets that are prefixed with Before or After are intended to be overridden in projects.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it correct to concatenate (pseudo-)random byte values before testing them with the NIST suite or tools like dieharder?
Let's assume I have thousands of (pseudo-)random 4-byte values. The values are 4 byte random values which a blackbox device gave me. I got these values by requesting them. In between others might have requested them too (I don't know about that). Now I'd like to test them for randomness. There are tools for this like dieharder or the NIST Statistical Test Suite.
Is it valid to just concatenate the thousands of 4-byte values so that I end up with one very long byte (n * 1000 * 4 byte) stream which I then feed into these tools?
Is it correct that it doesn't matter for the tests how long the individual values (4-byte) were before? (Because the test tool wouldn't know that I had 4-byte values in the beginning, once I concatenated them?).
Edit:
The question is meant as a general question. The actual underlying problem is how to examine seed values for randomness, which I obtained via UDS Security Access (see https://en.wikipedia.org/wiki/Unified_Diagnostic_Services#Services $27).
A:
Is it valid to just concatenate the thousands of 4-byte values so that I end up with one very long byte (n * 1000 * 4 byte) stream which I then feed into these tools?
Is it correct that it doesn't matter for the tests how long the individual values (4-byte) were before?
Yes for both. The fact that others may have obtained (and removed) randomness from the source while it was sampled, or/and that the samples are grouped in some particular way for testing, does not prevent from testing what's obtained. And that can not cause a valid test to fail more often, assuming the source's full output is indistinguishable from random (including for said others trying to make the test pass, or fail).
On the other hand, those same facts could make the test become arbitrarily less capable of detecting some faults. As an extreme example, a source that always repeat each byte that it outputs might become indistinguishable from true random if we sub-sample its output, keeping every odd byte.
The actual underlying problem is how to examine seed values for randomness.
Dieharder or the NIST Statistical Test Suite alone can't give any assurance of that. At best, they can indicate a fail with high confidence, which saves from performing further work (beyond checking that the test was correctly performed/works). If they indicate pass, no other firm conclusion can be reached on that basis alone. It is needed to know how the seed values are generated, and that can't be determined by a test of the seed values.
As a proof that these tests can not validate the fitness for cryptographic purposes of a source of unknown build, consider a RNG with:
a real-time clock keeping UTC time in second, initializing 128-bit register at startup after a delay of 1 second
with the register then repeatedly encrypted using AES-256 and a key to produce the next register value, which concatenated 128-bit values form the bulk of the output, queried over a gigabit Ethernet interface.
This source will pass any black-box testing that does not reject a good generator, including tests scrutinizing power-on, as long as the test does not use AES-256 and the correct key.
But this source is disastrous from a cryptographic perspective. Given the key and when the black box was started, its output is predictable. Given the key and a fragment of a sequence, all the rest can be computed. Some party eating bytes from the source in the background can even decide what another party using the source will get!
As pointed by others, many statistical tests, including some of the DieHarder suite, require megabytes of input. The full Dieharder needs gigabytes.
However, in the context of a cryptographic RNG of proper structure, these tests requiring a lot of input are not needed. The tests that make sense are those on the unconditioned (or lightly conditioned) entropy source, used to seed a CSPRNG. The source is validated by tests which purpose is to ensure that it delivers some entropy. The CSPRNG is validated by examination of its design, and Known Answer Tests. Some monitoring in the RNG should detect a fault in the source and in this case prevent output. The combination might be checked by an extra test of the whole thing, but that's meaningful only if there is some assurance, obtained otherwise, that the overall structure really is the source seeding the CSPRNG, and being monitored.
A:
Thousands of bytes isn't nearly enough samples for any powerful statistical test. The fewer samples you have the less sensitive a given test can be.
If you concatenate statistically independent uniform samples then tests should pass the resulting byte stream. It doesn't matter how the bits are rearranged as long as order doesn't depend on the value of those bits. (Reversing and bit interleaving but not rearranging bytes into ascending order.)
Some statistical tests aren't sensitive to order. Basic frequency tests and tests based on mean, median, variance, for example. However test suites include many different types of tests, some of which are order sensitive. Rearranged bits from an ideal random source should pass both order-sensitive and order-insensitive tests.
Different methods involving reordering are used in testing Non-Cryptographic RNGs. One improvement over a single pass over test data is to repeat the test with bit order reversed within each 32-bit word. This is documented in Sebastiano Vigna's papers involving RNG testing. This is done because the tests are less sensitive to patterns in low order bits and also because non-cryptographic RNGs are often "more" random in high bits and "less" random in low bits.
Round-robin interleaving of samples from multiple generators was done in a paper, "Better Splitable Pseudorandom Number Generators
(and Almost As Fast)" as hack to test RNGs from the same family for correlations. It isn't a totally reliable method for detecting such correlations.
Other kinds of modifications to the test suites' inputs will have the same effect as reordering as long as they do not introduce bias. For example, negating each bit of output, XORing the stream by a constant, or using modular addition with a constant.
A Good RNG Will Pass no matter how you mutate (without bias) its output. A bad RNG Might fail or Might Not before or after transforming (scrambling) its output some way.
Such transformations Do Not Turn an Insecure RNG into a Secure RNG. A bad RNG can pass all or some statistical tests after applying various mutations. That does not mean that the input is actually random or unpredictable.
Positive RNG test suite results (failing a "randomness" test) usually indicate data is not random. There are false positive but they can be detected by running the tests multiple times with different data. False negatives, however, are a very serious flaw in RNG test suites.
Passing any number of statistical tests will not tell you if an RNG or cipher is secure. It is Very Easy to make an algorithm with enough apparent randomness to pass any black-box statistical tests you subject it to, but it's Much Harder to design a secure algorithm.
The same applies to output from a hardware TRNG. In fact you cannot tell the difference between truly random output and output generated from, say, a counter encrypted with a secret key known only to the manufacturers of the device. (As in a backdoored RNG.) Statistical tests cannot tell you how much entropy a hardware RNG produces. Nor can they tell you whether a noisy source is actually unpredictable.
In summary:
Passing RNG tests Does Not mean the output is actually pattern-free, statistically unbiased, or secure.
Failing the tests persistently indicates a definite problem.
An unbiased transformation applied to a uniform IID bit string results in a new string which is also unbiased.
Scrambling output can hide statistical artifacts but it Cannot turn insecure RNGs into secure RNGs.
RNG test suites are practically Useless for cryptography
Something can be apparently random without actually being unpredictable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
gluCylinder() how works OpenGL
I wanted to build a cricket ground with OpenGL. I made several polygons to indicate field, pitch and bowling lines. But the problem is when I am trying to use gluCylinder to make stumps I made depth glEnable(GL_DEPTH_TEST), but my polygons are then not working. I just want to know how Can I use gluCylinder to make stumps with those polygons I have made.
I have following code, but want to add stumps here but I cant,
#include <GL/gl.h>
#include <GL/glut.h>
static double deg=0.0;
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT);
glRotatef(deg, 0.0, 0.0, 1.0); // Rotate by deg
// field
glColor3f (0.0, 0.5, 0.0);
glBegin(GL_POLYGON);
glVertex3f (0, 0, 0.0);
glVertex3f (1, 0, 0.0);
glVertex3f (1, 0.75, 0.0);
glVertex3f (0.8, 0.82, 0.0);
glVertex3f (0.6, 0.85, 0.0);
glVertex3f (0.4, 0.85, 0.0);
glVertex3f (0.2, 0.82, 0.0);
glVertex3f (0.0, 0.75, 0.0);
glEnd();
// pitch
glColor3f (0.25, 0.30, 0.0);
glBegin(GL_POLYGON);
glVertex3f(0.5,0.65,0.0);
glVertex3f(0.47,0.35,0.0);
glVertex3f(0.60,0.35,0.0);
glVertex3f(0.57,0.65,0.0);
glEnd();
//ump line
glColor3f (1.0, 1.0, 1.0);
glBegin(GL_POLYGON);
glVertex3f(0.49,0.63,0.0);
glVertex3f(0.49,0.6315,0.0);
glVertex3f(0.58,0.6315,0.0);
glVertex3f(0.58,0.63,0.0);
glEnd();
//bat line
glColor3f (1.0, 1.0, 1.0);
glBegin(GL_POLYGON);
glVertex3f(0.46,0.40,0.0);
glVertex3f(0.46,0.4025,0.0);
glVertex3f(0.61,0.4025,0.0);
glVertex3f(0.61,0.40,0.0);
glEnd();
glFlush ();
}
void init (void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}
void keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 27: // "esc" on keyboard
exit(0);
break;
case 97: // "a" on keyboard
deg = deg+5.0;
glutPostRedisplay();
break;
case 100:
deg = deg-5.0;
glutPostRedisplay();
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (600, 600);
glutInitWindowPosition (100, 100);
glutCreateWindow ("hello");
init ();
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
A:
glEnable(GL_DEPTH_TEST) requires a depth buffer. Make sure to allocate one via oring in GLUT_DEPTH in your glutInitDisplayMode() call.
Make sure to clear your new depth buffer via oring in GL_DEPTH_BUFFER_BIT in your glClear() call.
#include <GL/glut.h>
static double deg=0.0;
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotatef(deg, 0.0, 0.0, 1.0); // Rotate by deg
// field
glColor3f (0.0, 0.5, 0.0);
glBegin(GL_POLYGON);
glVertex3f (0, 0, 0.0);
glVertex3f (1, 0, 0.0);
glVertex3f (1, 0.75, 0.0);
glVertex3f (0.8, 0.82, 0.0);
glVertex3f (0.6, 0.85, 0.0);
glVertex3f (0.4, 0.85, 0.0);
glVertex3f (0.2, 0.82, 0.0);
glVertex3f (0.0, 0.75, 0.0);
glEnd();
// pitch
glColor3f (0.25, 0.30, 0.0);
glBegin(GL_POLYGON);
glVertex3f(0.5,0.65,0.0);
glVertex3f(0.47,0.35,0.0);
glVertex3f(0.60,0.35,0.0);
glVertex3f(0.57,0.65,0.0);
glEnd();
//ump line
glColor3f (1.0, 1.0, 1.0);
glBegin(GL_POLYGON);
glVertex3f(0.49,0.63,0.0);
glVertex3f(0.49,0.6315,0.0);
glVertex3f(0.58,0.6315,0.0);
glVertex3f(0.58,0.63,0.0);
glEnd();
//bat line
glColor3f (1.0, 1.0, 1.0);
glBegin(GL_POLYGON);
glVertex3f(0.46,0.40,0.0);
glVertex3f(0.46,0.4025,0.0);
glVertex3f(0.61,0.4025,0.0);
glVertex3f(0.61,0.40,0.0);
glEnd();
glPopMatrix();
glFlush ();
}
void init (void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 27: // "esc" on keyboard
exit(0);
break;
case 'a': // "a" on keyboard
deg = deg+5.0;
glutPostRedisplay();
break;
case 'z':
deg = deg-5.0;
glutPostRedisplay();
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize (600, 600);
glutInitWindowPosition (100, 100);
glutCreateWindow ("hello");
init ();
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
Be aware that GL_POLYGON only supports convex polygons.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed'
I am not sure why this is coming up. I am not serializing the XML, but my array that I created from an RSS feed (note this is just a snippet):
$game_data = array (
'sysreqos' => $game->systemreq->pc->sysreqos,
'sysreqmhz' => $game->systemreq->pc->sysreqmhz,
'sysreqmem' => $game->systemreq->pc->sysreqmem,
'sysreqdx' => $game->systemreq->pc->sysreqdx,
'sysreqhd' => $game->systemreq->pc->sysreqhd,
);
Then I serialize it $some_var = serialize($game_data) and write to a text file fputs($fh,$some_var).
But it does not get that far, it errors out on the serialize line:
Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed'
A:
You have to cast the XML data to a string because internally they are all SimpleXMLElements.
$game_data = array (
'sysreqos' => (string)$game->systemreq->pc->sysreqos,
'sysreqmhz' => (string)$game->systemreq->pc->sysreqmhz,
'sysreqmem' => (string)$game->systemreq->pc->sysreqmem,
'sysreqdx' => (string)$game->systemreq->pc->sysreqdx,
'sysreqhd' => (string)$game->systemreq->pc->sysreqhd
);
Or perhaps a little bit more elegant:
$game_data = array();
$properties = array('sysreqos', 'sysreqmhz', 'sysreqmem', 'sysreqdx', 'sysreqhd');
foreach ($properties as $p) {
$game_data[$p] = (string)$game->systemreq->pc->$p;
}
A:
In the Classes and Objects docs, there is this: In order to be able to unserialize() an object, the class of that object needs to be defined.
Prior to PHP 5.3, this was not an issue. But after PHP 5.3 an object made by SimpleXML_Load_String() cannot be serialized. An attempt to do so will result in a run-time failure, throwing an exception. If you store such an object in $_SESSION, you will get a post-execution error that says this:
Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed' in [no active file]:0 Stack trace: #0 {main} thrown in [no active file] on line 0
The entire contents of the session will be lost. Hope this saves someone some time!
<?php // RAY_temp_ser.php
error_reporting(E_ALL);
session_start();
var_dump($_SESSION);
$_SESSION['hello'] = 'World';
var_dump($_SESSION);
// AN XML STRING FOR TEST DATA
$xml = '<?xml version="1.0"?>
<families>
<parent>
<child index="1" value="Category 1">Child One</child>
</parent>
</families>';
// MAKE AN OBJECT (GIVES SimpleXMLElement)
$obj = SimpleXML_Load_String($xml);
// STORE THE OBJECT IN THE SESSION
$_SESSION['obj'] = $obj;
By: Ray.Paseur
Ref: http://php.net/manual/en/function.unserialize.php
what i do is as 'Stefan Gehrig' said, cast the XML data to a string
$_SESSION['obj'] = (string)$obj;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Convert HEX string to it's actual string value in c#
There is a 3rd party code, which returns me the string "Nmimtech1" in form of a byte[] array.
object password1 = pProps.GetProperty("PASSWORD");
(Its third party ESRI library code, so do not bother)
Now i convert it to byte[]
byte[] pswrdbyte = password1 as byte[]
The content of this byte array are
[0] 2 byte
[1] 0 byte
[2] 0 byte
[3] 0 byte
[4] 20 byte
[5] 0 byte
[6] 0 byte
[7] 0 byte
[8] 200 byte
[9] 115 byte
[10] 39 byte
[11] 180 byte
[12] 150 byte
[13] 100 byte
[14] 74 byte
[15] 44 byte
[16] 7 byte
[17] 215 byte
[18] 137 byte
[19] 50 byte
[20] 212 byte
[21] 138 byte
[22] 56 byte
[23] 241 byte
[24] 134 byte
[25] 51 byte
[26] 75 byte
[27] 0 byte
Now i have tried each and every way to convert it back to "Nmimtech1
string str = System.Text.Encoding.ASCII.GetString(pswrdbyte);
returns "\0\0\0\0\0\0?s'??dJ,\a??2??8??3K\0"
string str1 = System.Text.Encoding.Unicode.GetString(pswrdbyte);
returns "\0\0珈됧撖ⱊ휇㊉諔㎆K"
string str2 = System.Text.Encoding.UTF8.GetString(pswrdbyte);
returns "\0\0\0\0\0\0�s'��dJ,\a2Ԋ8�3K\0"
string str3 = System.Text.Encoding.UTF32.GetString(pswrdbyte);
returns "�����"
string str4 = System.Text.Encoding.UTF7.GetString(pswrdbyte);
returns "\0\0\0\0\0\0Ès'´dJ,\a×2Ô8ñ3K\0"
string str5 = System.Text.Encoding.BigEndianUnicode.GetString(pswrdbyte);
returns "Ȁ\0᐀\0졳➴除䨬ߗ褲풊㣱蘳䬀"
string str6 = pswrdbyte.ToString();
returns "System.Byte[]" (weird)
string s = BitConverter.ToString(pswrdbyte);
returns "02-00-00-00-14-00-00-00-C8-73-27-B4-96-64-4A-2C-07-D7-89-32-D4-8A-38-F1-86-33-4B-00". Now this makes a little sense, but can you tell me how to convert this hex string back to "Nmimtech1" programmatically?
A:
Sorry guys, The password returned from Thirdparty code is encrypted, and i figured out we cant decrypt it. Rather, to store it locally, i will need to store the encrypted form.
Thanks
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Clickable area is bigger than the button - XAML Windows Phone 8.1 Silverlight
Hi guys i have this button here:
As you can see the clickable area is larger than the button, being a dialer the button area goes across other buttons areas.
How can I make equal the button and clickable area ?
Sorry for the bad english.
Thanks a lot.
Here is the XAML:
<Grid x:Name="ContentPanel">
<Grid.RowDefinitions>
<RowDefinition Height="0*"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFFA9E4F" Offset="0"/>
<GradientStop Color="#FFFE5D00" Offset="1"/>
</LinearGradientBrush>
</Grid.Background>
<Button x:Name="button1" Content="1" Margin="-12,267,306,0" Grid.Row="1" Click="button1_Click" Height="104" VerticalAlignment="Top" BorderThickness="0,3,3,3" FontSize="48" BorderBrush="#FFCFCFCF" Foreground="White" FontFamily="DengXian"/>
<Button x:Name="button2" Content="2" Margin="148,267,145,0" Grid.Row="1" Click="button2_Click" Height="104" VerticalAlignment="Top" FontSize="48" BorderBrush="#FFCFCFCF" Foreground="White" FontFamily="DengXian"/>
<Button x:Name="button3" Content="3" Margin="307,267,-12,0" Grid.Row="1" Click="button3_Click" Height="104" VerticalAlignment="Top" BorderThickness="3,3,0,3" FontSize="48" BorderBrush="#FFCFCFCF" Foreground="White" FontFamily="DengXian" Padding="0" UseLayoutRounding="True" FlowDirection="LeftToRight"/>
<Button x:Name="button4" Content="4" Height="104" Margin="-12,344,306,0" Grid.Row="1" VerticalAlignment="Top" Click="button4_Click" BorderThickness="0,3,3,3" FontSize="48" BorderBrush="#FFCFCFCF" Foreground="White" FontFamily="DengXian"/>
<Button x:Name="button5" Content="5" Height="104" Margin="148,344,145,0" Grid.Row="1" VerticalAlignment="Top" Click="button5_Click" FontSize="48" BorderBrush="#FFCFCFCF" Foreground="White" FontFamily="DengXian"/>
<Button x:Name="button6" Content="6" Height="104" Margin="307,344,-12,0" Grid.Row="1" VerticalAlignment="Top" Click="button6_Click" BorderThickness="3,3,0,3" FontSize="48" BorderBrush="#FFCFCFCF" Foreground="White" FontFamily="DengXian"/>
<Button x:Name="button7" Content="7" Height="104" Margin="-12,421,306,0" Grid.Row="1" VerticalAlignment="Top" Click="button7_Click" BorderThickness="0,3,3,3" FontSize="48" BorderBrush="#FFCFCFCF" Foreground="White" FontFamily="DengXian"/>
<Button x:Name="button8" Content="8" Height="104" Margin="148,421,145,0" Grid.Row="1" VerticalAlignment="Top" Click="button8_Click" FontSize="48" BorderBrush="#FFCFCFCF" Foreground="White" FontFamily="DengXian"/>
<Button x:Name="button9" Content="9" Height="104" Margin="307,421,-12,0" Grid.Row="1" VerticalAlignment="Top" Click="button9_Click" BorderThickness="3,3,0,3" FontSize="48" BorderBrush="#FFCFCFCF" Foreground="White" FontFamily="DengXian"/>
<Button x:Name="button0" Content="0" Height="104" Margin="148,498,145,0" Grid.Row="1" VerticalAlignment="Top" Click="button0_Click" FontSize="48" BorderBrush="#FFCFCFCF" Foreground="White" FontFamily="DengXian"/>
<Button x:Name="buttonCanc" Content="#" Height="104" Margin="-12,498,306,0" Grid.Row="1" VerticalAlignment="Top" Click="buttonCanc_Click" BorderThickness="0,3,3,3" FontSize="48" BorderBrush="#FFCFCFCF" Foreground="White" FontFamily="DengXian"/>
<Button x:Name="buttonAst" Content="*" Height="104" Margin="307,498,-12,0" Grid.Row="1" VerticalAlignment="Top" Click="buttonAst_Click" BorderThickness="3,3,0,3" FontSize="80" BorderBrush="#FFCFCFCF" Foreground="White" FontFamily="DengXian"/>
<Button x:Name="buttonMakeCall" Content="" Height="110" Margin="-12,576,225,0" Grid.RowSpan="2" VerticalAlignment="Top" Click="buttonMakeCall_Click" BorderThickness="0,3" d:LayoutOverrides="LeftPosition, RightPosition" BorderBrush="#FFCFCFCF">
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource="/Assets/call.png"/>
</Button.Background>
</Button>
<Button x:Name="buttonBackspace" Content="" HorizontalAlignment="Left" Height="110" Margin="228,576,-12,0" Grid.RowSpan="2" VerticalAlignment="Top" Width="264" Click="buttonBackspace_Click" BorderThickness="0,3" BorderBrush="#FFCFCFCF" >
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource="/Assets/backspace.png"/>
</Button.Background>
</Button>
<Image x:Name="image" Height="80" Grid.RowSpan="2" VerticalAlignment="Top" Source="/Assets/BarraWind.png"/>
<Button x:Name="buttonCall" Padding="0" Content="" HorizontalAlignment="Left" Height="118" Margin="-12,662,0,-12" Grid.Row="1" VerticalAlignment="Top" Width="145" BorderThickness="0,5,0,0" BorderBrush="#FF003AFF">
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource="/Assets/chiamamenu.jpg"/>
</Button.Background>
</Button>
<Button x:Name="buttonRubPers" Padding="0" Content="" Height="118" Margin="107,662,228,-12" Grid.Row="1" VerticalAlignment="Top" BorderThickness="0,5,0,0" Click="buttonRubPers_Click" BorderBrush="#FFFC670D">
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource="/Assets/rubricapersonalemenu.jpg"/>
</Button.Background>
</Button>
<Button x:Name="buttonRubAz" Padding="0" Content="" Height="118" Margin="228,662,107,-12" Grid.Row="1" VerticalAlignment="Top" Click="buttonRubAz_Click" BorderThickness="0,5,0,0" BorderBrush="#FFFC670D">
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource="/Assets/rubricaaziendalemenu.jpg"/>
</Button.Background>
</Button>
<Button x:Name="buttonRegCall" Padding="0" Content="" HorizontalAlignment="Right" Height="118" Margin="0,662,-13,-12" Grid.Row="1" VerticalAlignment="Top" Width="145" BorderThickness="0,5,0,0" Click="buttonRegCall_Click" Foreground="#FFFC670D" BorderBrush="#FFFC670D">
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource="/Assets/archiviochiamatemenu.jpg"/>
</Button.Background>
</Button>
<Border BorderThickness="0,3" HorizontalAlignment="Left" Height="202" Margin="0,80,0,0" Grid.RowSpan="2" VerticalAlignment="Top" Width="480" Background="#FFFF5D00" BorderBrush="#FFCFCFCF"/>
<TextBlock x:Name="textBoxCal" Height="178" Margin="10,92,10,0" Grid.RowSpan="2" TextWrapping="Wrap" VerticalAlignment="Top" Foreground="Black" FontSize="48" FontFamily="Microsoft YaHei UI" TextAlignment="Center"/>
<Border x:Name="BorderToast" BorderBrush="#FF0120BA" BorderThickness="5" Margin="90,172,90,347" Grid.RowSpan="2" CornerRadius="10" Background="Gainsboro" d:LayoutOverrides="TopPosition, BottomPosition" Visibility="Collapsed"/>
<TextBlock x:Name="textBlock1" Height="92" Margin="103,183,103,0" TextWrapping="Wrap" VerticalAlignment="Top" Foreground="#FFFF5D00" FontSize="34.667" TextAlignment="Center" FontFamily="Microsoft YaHei UI" Grid.RowSpan="2" Text="STO CHIAMANDO" FontWeight="Bold" Visibility="Collapsed"/>
<TextBlock x:Name="textToast" Height="64" Margin="97,277,97,0" TextWrapping="Wrap" VerticalAlignment="Top" Foreground="#FF0C00FF" FontSize="42.667" TextAlignment="Center" FontFamily="Microsoft YaHei UI" Grid.RowSpan="2" Text="3468787890" Visibility="Collapsed"/>
<Controls:ProgressRing x:Name="ProgRing" Margin="199,340,199,370" Grid.RowSpan="2" IsActive="True" Foreground="#FFFF5D00" Visibility="Collapsed"/>
</Grid>
A:
Unfortunatelly you have to change the whole template for your Buttons. The default one has a Border with
Margin="{StaticResource PhoneTouchTargetOverhang}"
which is this 12 pixels on each side.
Read about creating a custom style (and how to get the default template): http://www.geekchamp.com/tips/custom-styles-and-templates-in-windows-phone-button
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Load half word and load byte in a single cycle datapath
There was this problem that has been asked about implementing a load byte into a single cycle datapath without having to change the data memory, and the solution was something below.
alt text http://img214.imageshack.us/img214/7107/99897101.jpg
This is actually quite a realistic
question; most memory systems are
entirely word-based, and individual
bytes are typically only dealt with
inside the processor. When you see a
“bus error” on many computers, this
often means that the processor tried
to access a memory address that was
not properly word-aligned, and the
memory system raised an exception.
Anyway, because byte addresses might
not be a multiple of 4, we cannot pass
them to memory directly. However, we
can still get at any byte, because
every byte can be found within some
word, and all word addresses are
multiples of 4. So the first thing we
do is to make sure we get the right
word. If we take the high 30 bits of
the address (i.e., ALUresult[31-2])
and combine them with two 0 bits at
the low end (this is what the “left
shift 2” unit is really doing), we
have the byte address of the word that
contains the desired byte. This is
just the byte’s own address, rounded
down to a multiple of 4. This change
means that lw will now also round
addresses down to multiples of 4, but
that’s OK since non-aligned addresses
wouldn’t work for lw anyway with this
memory unit. OK, now we get the data
word back from memory. How do we get
the byte we want out of it? Well,
note that the byte’s byte-offset
within the word is just given by the
low-order 2 bits of the byte’s
address. So, we simply use those 2
bits to select the appropriate byte
out of the word using a mux. Note the
use of big-endian byte numbering, as
is appropriate for MIPS. Next, we
have to zero-extend the byte to 32
bits (i.e., just combine it with 24
zeros at its high end), because the
problem specifies to do so. Actually,
this was a slight mistake in the
question: in reality, the lbu
instruction zero-extends the byte, but
lb sign-extends it. Oh, well.
Finally, we have to extend the
MemtoReg-controlled mux to accept one
new input: the zero-extended byte for
the lb case. The MemtoReg control
signal must be widened to 2 bits. The
original 0 and 1 cases change to 00
and 01, respectively, and we add a new
case 10 which is only used in the case
of lb.
I don't quite actually understand on how this works even after reading the explanation, especially about left shift the ALU result by 2 would give the byte address... how is this possible?? so if I would like to load a half word then I would do one left shift and I would get the address of the half word?? what would be a better way to do load byte, load half word by modifying the data memory? (the question above puts constraints that we can't modify the data memory)
A:
The original author simply seems to be adding a byte multiplexer to the 32-bit data being read from the memory. This memory allows a full 32-bit naturally aligned load (lw instruction) and the additional byte multiplexer and zero extension allows for load byte instructions as well (lbu instruction).
The left shift of the ALU result yields a word address, NOT a byte address, and accounts for the implicit right shift by two in the signal routing. The end result is simply the lower two bits of the ALU result being masked (zeroed) before being sent to the memory. The two LSBs of the ALU value are fed down-stream of the memory to the byte multiplexer, allowing the word memory to read arbitrary bytes.
There is no direct support in the logic shown for loading half-words (16-bits), just bytes and full 32-bit words. You could, however, easily modify the byte addressing logic to support words instead of bytes (or even both) using a similar approach.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Coding standards for long strings?
I've been looking for some official guidelines on how to format long strings in module code, but the closest thing I've found is an ambiguous section on indenting long SQL queries which suggests any of the following styles:
$text = '
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula odio,
hendrerit consectetur porta vitae, sollicitudin sit amet eros. Integer
hendrerit varius felis id dignissim.
';
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula'
. 'odio, hendrerit consectetur porta vitae, sollicitudin sit amet eros. Integer'
. 'hendrerit varius felis id dignissim.'
;
$text = <<<TEXT
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula odio,
hendrerit consectetur porta vitae, sollicitudin sit amet eros. Integer
hendrerit varius felis id dignissim.
TEXT;
The Drupal Coding Standards talk about how to use the concatenation assignment operator:
$string .= 'Foo';
$string .= $bar;
$string .= baz();
but they don't actually state whether single long strings should be broken up that way.
To add further confusion, the Coder module handles long strings differently again in its "good.php" test file:
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ' .
'ligula odio, hendrerit consectetur porta vitae, sollicitudin sit ' .
'amet eros. Integer hendrerit varius felis id dignissim.';
Personally, I've just been doing it like this until now:
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula
odio, hendrerit consectetur porta vitae, sollicitudin sit amet eros.
Integer hendrerit varius felis id dignissim.';
However, I'd like to start doing it the "right" way (if there is one). Does anyone have a definitive answer?
A:
Drupal does not restrict the usage of long strings in code. It is advisable to concatenate each line ($output .= '...';) for a readable code, but as you can see in Drupal code, long strings are not broken up, especially when used with t():
function field_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.field':
$field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#';
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Field module allows custom data fields to be defined for <em>entity</em> types (see below). The Field module takes care of storing, loading, editing, and rendering field data. Most users will not interact with the Field module directly, but will instead use the <a href=":field-ui-help">Field UI module</a> user interface. Module developers can use the Field API to make new entity types "fieldable" and thus allow fields to be attached to them. For more information, see the <a href=":field">online documentation for the Field module</a>.', array(':field-ui-help' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) :'#', ':field' => 'https://www.drupal.org/documentation/modules/field')). '</p>';
$output .= '<h3>' . t('Terminology') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Entities and entity types') . '</dt>';
$output .= '<dd>' . t('The website\'s content and configuration is managed using <em>entities</em>, which are grouped into <em>entity types</em>. <em>Content entity types</em> are the entity types for site content (such as the main site content, comments, custom blocks, taxonomy terms, and user accounts). <em>Configuration entity types</em> are used to store configuration information for your site, such as individual views in the Views module, and settings for your main site content types.') . '</dd>';
$output .= '<dt>' . t('Entity sub-types') . '</dt>';
$output .= '<dd>' . t('Some content entity types are further grouped into sub-types (for example, you could have article and page content types within the main site content entity type, and tag and category vocabularies within the taxonomy term entity type); other entity types, such as user accounts, do not have sub-types. Programmers use the term <em>bundle</em> for entity sub-types.') . '</dd>';
$output .= '<dt>' . t('Fields and field types') . '</dt>';
$output .= '<dd>' . t('Content entity types and sub-types store most of their text, file, and other information in <em>fields</em>. Fields are grouped by <em>field type</em>; field types define what type of data can be stored in that field, such as text, images, or taxonomy term references.') . '</dd>';
I would stick with this drupal usage, this is the best compromise for usage and good readability. Your first examples looks good, but adds extra line feeds. The second example is not good to read and the third is often used in scripts, but not very common in php code.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is this method of display images called?
On Google Images, some images are loaded like this:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBhQSEBQUEhQVFRQWFBQXFRYVFRQQFhIUFBQXFRYWFxQYHCYfGBkjGRcUHy8gIycpLCwsFR4xNTAqNSYrLCkBCQoKDgwOGg8PGi8kHyQyLCwsLCwtLiwsLC0sKSwsLCwsKSwsLCosLCwpLCwsLCksLCwsLCwsLCwsLCwsKSwsLP/AABEIAOQA2AMBIgACEQEDEQH/xAAcAAEAAgMBAQEAAAAAAAAAAAAABgcBBAUDCAL/xABEEAABAwEFAwgHBQYGAwEAAAABAAIDEQQFEiExBkFRBxMiYXGBkaEjMlJyscHRFCRCYpJzgqKywvAWM0Nj4fFTZMMV/8QAGwEBAAIDAQEAAAAAAAAAAAAAAAQFAgMGAQf/xAA0EQACAgIABAQEAwcFAAAAAAAAAQIDBBEFEiExE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NHYCfoutd92tiBpmTqTv7tyncO4RkO6M8iPlXuaMjKi4tRfU2wFlYosrtypCIiAIiIAiIgCwVxr7v3mXhgLQ4ivS8MguS+8ZH/6ju44fgtUrUuh5s9L923bFao7O0Vc57Q460BFTQDgN6qS3yDnC4Eh8mEujcMmubGAaEkUqa0Hd1L3vTaJjLVOC2XCZHc4BixyuBp03nRg3NGWdc163bZW2h/RdDCNwLHSP/iAHmo8pNkC6UrPKlsk/J3tVZ7NDM2Uua8vBDQ2SRz6MFThocNDlnwVkXVebLREJI64XcRQjfmPBV7DcDQ2jpJHAjOhbED3MA69+9S/Zm82ECBoaMDOjhNaNbQUNTrmM1sqm+zJFEZQSi+x30RFJJBgqtdr9mLRz8kjIzIx7sQLM3NrqC3XvCsqiUWq2pWLTJeJlzxZ88CiJoXN9Zrmn8zXN+IWlJM2vrD9QX0IWheRsbDqxv6Qojwv+xfw+Idd6/6/2KDhlFcnDucPkV0LJdssh9HE93usdTxpRXa2ysGjWjsAC9KIsL3ZjZ8Qt/LX+L/sRjYm4ZLO17pQGufho2tS0NrqRlXPRSdZoimwgoR5Uc5ddK6bnLuzCLKLM1BERAEREAREQBERAFhZRAVxymAGVoI/AKdeZUIitTmeo4jvP1V6W+7Ipm4ZWNePzCtOw6juUbtPJnZHVLedZ7r6gdzgVFnS29ohX0Tk+aLKltk75D0jXuB8zmvOzQ4TXXqJNPIhWe/kli3TyjtbGf6Qsx8k8Q1nlPY2NvyKx8KZC/Y7W9/cgQlJAGVBSlBw4nUlTXk5Pp3U/wDGa/qbT5+C7Vk5ObIzUSP955p4NopFYrvjhbhiY1g4NFK9vFZQpae2S6cecZc0me6LKKUTwiIgCIiAIiIAiIgCIiAIiIAiIgCIiAIiIAiIgCwiIAiIh4FlEQ9CIiA//9k=
What is this called? I want to find some more information about it (eg. how well is it supported? Is it faster than traditional images?).
A:
This is the Data URI schema, defined in RFC 2397.
In this specific case the image is base64 encoded and embedded in the page/css.
Doing this (Base64 encoding) increases the size of the data (by about 30%), but the data URI avoids an additional request to the server which in many cases would cause the complete page to load faster.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python: get the most maximum values from dictionary
I have a dictionary
{u'__': 2, u'\u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430': 1, u'\u041f\u043e\u0447\u0435\u043c\u0443': 1, u'\u041d\u0430\u043c': 1, u'\u043e\u0434\u0438\u043d': 1, u'\u0441\u043e\u0432\u0435\u0442\u0430\u043c\u0438': 1, u'\u041f\u0440\u043e\u0438\u0437\u043d\u0435\u0441\u0442\u0438': 1, u'\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e,': 1, u'\u0432\u044b\u0445\u043e\u0434\u044f\u0449\u0435\u043c\u0443': 1, u'\u043d\u0430\u0448\u0435\u0439': 2, u'\u0441\u0438\u0441\u0442\u0435\u043c\u0443': 1, u'\u0441\u0431\u043e\u0440\u0430': 1, u'\u0434\u0430\u043b\u044c\u043d\u0435\u0439\u0448\u0435\u043c.': 1, u'[](//www.yandex.ru)': 1, u'\u0412\u0430\u043c': 1, u'\u0430': 102, u'\u0432\u0438\u0440\u0443\u0441\u043e\u0432,': 1, u'\u043e\u0447\u0435\u043d\u044c': 1, u'\u0438': 90, u'\u0440\u0430\u0437.': 1, u'[cureit](http://www.freedrweb.com/?lng=ru)': 1, u'\u043d\u0435': 9, u'\u0438\u043b\u0438': 2, u'\u0441\u043f\u0435\u0446\u0438\u0430\u043b\u044c\u043d\u043e': 1, u'\u043d\u0430': 11, u'\u043d\u043e': 17, u'\u0443\u0441\u0442\u0430\u043d\u043e\u0432\u043b\u0435\u043d\u044b': 1, u'\u041c\u043e\u0436\u0435\u0442': 1, u'\u0432\u0430\u0448': 5, u'\u0445\u043e\u0442\u0438\u0442\u0435': 1, u'[\u0444\u043e\u0440\u043c\u043e\u0439': 1, u'\u0432\u044b': 5, u'\u0446\u0435\u043b\u0435\u0439': 1, u'\u0441\u0438\u043c\u0432\u043e\u043b\u044b': 3, u'\u0415\u0441\u043b\u0438': 2, u'\u0422\u0430\u043a\u0436\u0435': 1, u'\u0432\u043e\u0437\u043d\u0438\u043a\u043b\u0438': 1, u'\u0434\u0430\u043d\u043d\u043e\u0433\u043e': 1, u'**\u0412': 1, u'\u0437\u0430\u043f\u0440\u043e\u0441\u044b),': 1, u'\u041f\u043e\u043c\u043e\u0449\u0438](//help.yandex.ru/common/?id=1111120).': 1, u'\u042f\u043d\u0434\u0435\u043a\u0441\u0443': 1, u'\u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0435': 2, u'\u0432': 69, u'\u0441\u0435\u0440\u0432\u0438\u0441\u043e\u043c': 1, u'\u043f\u043e\u043f\u0440\u043e\u0431\u0443\u0439\u0442\u0435': 1, u'\u0443\u0442\u0438\u043b\u0438\u0442\u043e\u0439': 1, u'\u0430\u0432\u0442\u043e\u043c\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0435': 4, u'\u0432\u043e\u043f\u0440\u043e\u0441': 1, u'\u0430\u0432\u0442\u043e\u043c\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0435.': 1, u'\u043f\u043e': 24, u'##': 1, u'\u0434\u043e\u0441\u0442\u0443\u043f': 1, u'\u0443': 37, u'(\u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440,': 1, u'\u0437\u0430\u043f\u043e\u043c\u043d\u0438\u0442\u044c': 1, u'\u2192': 1, u'\u042f\u043d\u0434\u0435\u043a\u0441': 4, u'\u0441\u043b\u0443\u0447\u0430\u0435': 2, u'\u043f\u043e\u0445\u043e\u0436\u0438': 1, u'\u043a\u0430\u043f\u0447\u0435\u0439': 1, u'\xab\u041e\u0442\u043f\u0440\u0430\u0432\u0438\u0442\u044c\xbb.': 1, u'#': 3, u'cookies**.': 1, u'\u0431\u0443\u0434\u0435\u0442': 1, u'\u0427\u0442\u043e\u0431\u044b': 2, u'\u0441\u0432\u044f\u0437\u0438](//feedback2.yandex.ru/captcha/).': 1, u'\u043f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c': 1, u'\u0434\u0440\u0443\u0433\u043e\u043c\u0443': 1, u'\u043f\u0440\u043e\u0431\u043b\u0435\u043c\u044b': 1, u'\u0432\u0430\u043c,': 1, u'\u0441\u043b\u0435\u0432\u0430\u041e\u0442\u043f\u0440\u0430\u0432\u0438\u0442\u044c': 1, u'\u043c\u043e\u0433\u0443\u0442': 1, u'\u0432\u044b\u0445\u043e\u0434\u044f\u0449\u0438\u0445': 1, u'\u0432\u0440\u0435\u043c\u0435\u043d\u043d\u043e': 1, u'\u0441\u043b\u0443\u0436\u0431\u0435': 1, u'ip-\u0430\u0434\u0440\u0435\u0441\u0430,': 1, u'\u043f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430,': 2, u'\u0430\u043d\u0442\u0438\u0432\u0438\u0440\u0443\u0441\u043d\u043e\u0439': 1, u'\u0432\u0430\u043c\u0438': 1, u'\u0435\u0433\u043e': 4, u'\u0437\u0430\u0434\u0430\u0442\u044c': 1, u'\u0442\u0430\u043a': 1, u'\u0440\u0430\u0437': 3, u'\u0441\u0435\u0442\u044c': 1, u'\u0441\u0442\u043e\u0438\u0442': 1, u'cookies,': 1, u'ip-\u0430\u0434\u0440\u0435\u0441\u0430.': 1, u'\u0437\u0430\u0440\u0430\u0436\u0435\u043d': 1, u'\u043d\u0430\u0436\u043c\u0438\u0442\u0435': 1, u'\u0437\u0430\u0431\u043b\u043e\u043a\u0438\u0440\u043e\u0432\u0430\u0442\u044c': 1, u'\u0434\u043b\u044f': 2, u'\u043e\u0439...': 1, u'[\u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0435': 1, u'\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044e,': 1, u'\u0438\u0445.': 1, u'\u044d\u0442\u0438\u0445': 1, u'\u043f\u0440\u043e\u0434\u043e\u043b\u0436\u0438\u0442\u044c': 1, u'\u043e\u0431': 9, u'\u043f\u043e\u0438\u0441\u043a,': 1, u'\u0440\u043e\u0434\u0443': 1, u'\u0434\u043e\u0432\u043e\u043b\u044c\u043d\u043e': 1, u'\u0412': 6, u'\u0441\u043b\u0443\u0447\u0438\u043b\u043e\u0441\u044c?': 1, u'\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u0435\u0439,': 1, u'\u0432\u044b\u043d\u0443\u0436\u0434\u0435\u043d\u044b': 1, u'\u043f\u043e\u043b\u0435': 1, u'\u043f\u043e\u0441\u0442\u0443\u043f\u0438\u0432\u0448\u0438\u0435': 1, u'\u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0438': 1, u'\u043a': 30, u'\u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u0446\u0438\u0440\u043e\u0432\u0430\u0442\u044c': 1, u'\u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044e\u0449\u0435\u0439': 1, u'\u041d\u0435\u0432\u0435\u0440\u043d\u043e,': 1, u'ip.': 1, u'\u0434\u0440\u0443\u0433\u0438\u0445': 1, u'\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0442\u0435\u043b\u044c\u043d\u043e': 1, u'\u043e\u0442\u043a\u043b\u044e\u0447\u0435\u043d\u044b': 1, u'\u0440\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u0430\u043d\u043d\u044b\u043c': 1, u'\u043d\u0430\u043b\u0438\u0447\u0438\u0435': 1, u'\u0432\u0432\u0435\u0434\u0438\u0442\u0435': 1, u'\u0434\u043e\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f,': 1, u'\u043f\u043e\u0441\u043b\u0435': 1, u'\u0432\u0430\u0448\u0435\u0433\u043e': 2, u'\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e': 1, u'': 1, u'\u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u0430,': 1, u'\u0440\u0435\u043a\u043e\u043c\u0435\u043d\u0434\u0443\u0435\u043c': 2, u'\u0436\u0430\u043b\u044c,': 1, u'\u0432\u0432\u043e\u0434\u0430': 1, u'\u043e\u0442\u043a\u043b\u044e\u0447\u0438\u0442\u044c': 1, u'\u043e\u0442': 9, u'\u0437\u0430\u0434\u0430\u0432\u0430\u0442\u044c': 1, u'\u0447\u0435\u0433\u043e': 1, u'\u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440,': 2, u'\u0437\u0430\u043f\u0440\u043e\u0441\u044b,': 1, u'\u044d\u0442\u043e\u043c': 3, u'\u0437\u043d\u0430\u0435\u0442\u0435': 1, u'\u044d\u0442\u043e\u0439': 1, u'\u0435\u0449\u0451': 1, u'\u0444\u0430\u0439\u043b\u044b': 1, u'\u043a\u043e\u0442\u043e\u0440\u044b\u0435': 1, u'\u0441\u043c\u043e\u0436\u0435\u0442': 1, u'\u0434\u043e\u043b\u0433\u043e.': 1, u'\u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e': 2, u'\u041f\u043e': 3, u'\u0434\u0435\u044f\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u0438': 1, u'\u043e\u0442\u043b\u0438\u0447\u0430\u0442\u044c': 1, u'\u0432\u0430\u0448\u0435\u043c': 2, u'\u043e\u0442\u043f\u0440\u0430\u0432\u043b\u044f\u0442\u044c': 1, u'\u0432\u0432\u0435\u0441\u0442\u0438': 1, u'\u0437\u0430\u043f\u043e\u043c\u043d\u0438\u043c': 1, u'\u0432\u0430\u0441': 4, u'': 1, u'\u0432\u0438\u0440\u0443\u0441\u043d\u043e\u0439': 2, u'\u0412\u043e\u0437\u043c\u043e\u0436\u043d\u043e,': 2, u'\u043f\u043e\u0434\u0434\u0435\u0440\u0436\u043a\u0438,': 1, u'\u0437\u0430\u043f\u0440\u043e\u0441\u044b': 5, u'\u043e\u0431\u0440\u0430\u0442\u043d\u043e\u0439': 1, u'\u0441': 77, u'\u0444\u043e\u0440\u043c\u0443,': 1, u'\u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440': 2, u'\u043f\u043e\u0441\u0442\u0443\u043f\u0430\u044e\u0442': 1, u'\u0432\u0430\u043c': 5, u'\u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u043e\u0439,': 1, u'\u0447\u0442\u043e': 1, u'\u0432\u043e\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c\u0441\u044f': 1, u'\u043f\u043e\u0438\u0441\u043a\u0443.': 2, u'\u0431\u044b\u0442\u044c,': 1, u'\u0441\u043c\u043e\u0436\u0435\u043c': 1, u'\u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435': 1, u'\u0432\u043e\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0439\u0442\u0435\u0441\u044c': 2, u'\xabdr.web\xbb.': 1, u'\u0432\u043a\u043b\u044e\u0447\u0438\u0442\u044c': 1, u'[\u042f\u043d\u0434\u0435\u043a\u0441.xml](//xml.yandex.ru).': 1, u'\u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u0438.': 1, u'\u043f\u0440\u0438\u0447\u0438\u043d\u0435': 1, u'\u0431\u0435\u0441\u043f\u043e\u043a\u043e\u0438\u0442\u044c': 1, u'\u043c\u044b': 3, u'\u043e\u0434\u043d\u043e\u0433\u043e': 1, u'\u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0430\u0442': 1}
I need to convert it encoding and get dictionary with 10 the biggest values.
I try to use
print max(dict.iteritems(), key=operator.itemgetter(10))[0]
But it returns me nothing.
But how convert this string I don't know. I didn't find the way to do it.
A:
max() can only ever return a single value. Use a Counter:
from collections import Counter
counter = Counter(yourdictionary)
print(counter.most_common(10))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Valgrind leak and Segmentation Error with a specific output when trying to malloc
So I have a program that receives as input a string with the format a word1 word2 word3 and that inserts these words into a structure that finally goes into a linked list. With all the inputs I have tried it works perfectly and there are no memory leaks but with this specific output I get a Segmentation Error as well as memory leak and it's almost surely because of the length of word1.
This is the input:
a
Adolph_Blaine_Charles_David_Earl_Frederick_Gerald_Hubert_Irvin_John_Kenneth_Lloyd_Martin_Nero_Oliver_Paul_Quincy_Randolph_Sherman_Thomas_Uncas_Victor_William_Xerxes_Yancy_Zeus_Wolfeschlegelsteinhausenbergerdorffwelchevoralternwarengewissenhaftschaferswessenschafewarenwohlgepflegeundsorgfaltigkeitbeschutzenvorangreifendurchihrraubgierigfeindewelchevoralternzwolfhunderttausendjahresvorandieerscheinenvonderersteerdemenschderraumschiffgenachtmittungsteinundsiebeniridiumelektrischmotorsgebrauchlichtalsseinursprungvonkraftgestartseinlangefahrthinzwischensternartigraumaufdersuchennachbarschaftdersternwelchegehabtbewohnbarplanetenkreisedrehensichundwohinderneuerassevonverstandigmenschlichkeitkonntefortpflanzenundsicherfreuenanlebenslanglichfreudeundruhemitnichteinfurchtvorangreifenvorandererintelligentgeschopfsvonhinzwischensternartigraum foo@bar.zp 2
Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXINPUT 682
typedef struct words {
char *word1;
char *word2;
char *word3;
} words;
typedef struct node{
words cont;
struct node *next;
} node;
typedef node *link;
link head;
void add(char c[]) {
words x;
char *str;
link temp = (link)malloc(sizeof(node));
strtok(c, " ");
str = strtok(NULL, " ");
x.word1 = (char *)malloc(sizeof(char) * (strlen(str) + 1));
strcpy(x.word1, str);
str = strtok(NULL, " ");
x.word2 = (char *)malloc(sizeof(char) * (strlen(str) + 1)); /* where the error happens with this input */
strcpy(x.word2, str);
str = strtok(NULL, "\0");
x.word3 = (char *)malloc(sizeof(char) * (strlen(str) + 1));
strcpy(x.word3, str);
temp->cont = x;
temp->next = head;
head = temp;
}
int main() {
char input[MAXINPUT] = " ";
head = NULL;
while (input[0] != 'x') {
fgets(input, MAXINPUT, stdin);
input[strcspn(input, "\r\n")] = 0;
if (input[0] == 'a')
add(input);
...
When I run this input with this code I get a Segmentation Error and valgrind says that there are 3 allocs and only one free and and that the leak\error happens in the line mentioned in the code, specifically with the strlen. It also says I can't access the memory position 0x0 for some reason. I wanted to know why this happens, Thanks!
A:
You do not test if strtok did find all the tokens. You must check the pointer returned by strtok() before using it. If you don't, invalid input will cause undefined behavior.
In your case, the input is longer than 682 bytes, the first 681 bytes are read into the array and this fragment does not contain enough tokens, making one of the strtok() calls to return NULL, causing undefined behavior when you dereference this null pointer with strlen().
Always test and report error conditions, you will save yourself countless hours of debugging time.
When the program crashes, the memory leaks reported by valgrind are meaningless because the program did not complete its normal execution and of course did not free allocated memory properly. The memory is still returned to the operating system after program exit, but valgrind reports the blocks that have not been freed by calling free().
To avoid setting an arbitrary limit to the line length, you can use the POSIX standard function getline() that re-allocates the array as needed.
You should also use strdup to allocate copies of the strings in a single function call:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct words {
char *word1;
char *word2;
char *word3;
} words;
typedef struct node{
words cont;
struct node *next;
} node;
typedef node *link; // hiding pointers behind typedefs is not recommended
link head;
link add(char c[]) {
words x = { NULL, NULL, NULL };
char *str;
link temp;
if (strtok(c, " ") != NULL
&& (str = strtok(NULL, " ")) != NULL
&& (x.word1 = strdup(str)) != NULL
&& (str = strtok(NULL, " ")) != NULL
&& (x.word2 = strdup(str)) != NULL
&& (str = strtok(NULL, "")) != NULL
&& (x.word3 = strdup(str)) != NULL
&& (temp = malloc(sizeof(*temp)) != NULL) {
temp->cont = x;
temp->next = head;
return head = temp;
} else {
free(x.word3);
free(x.word2);
free(x.word1);
return NULL;
}
}
int main() {
char *input = NULL;
size_t input_size = 0;
head = NULL;
while (getline(&input, &input_size, stdin) >= 0 && *input != 'x') {
input[strcspn(input, "\r\n")] = '\0';
if (*input == 'a')
add(input);
...
}
...
}
free(input);
...
return 0;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Naming amitriptyline by IUPAC
Can someone guide me through step by step how amitriptyline is named by IUPAC?
I know the name per se, but it is very confusing to me, and I'd like someone to explain it to me. The systematic name is
3-(10,11-Dihydro-5H-dibenzo[a,d]cycloheptene-5-ylidene)-N,N-dimethylpropan-1-amine.
A:
Note: As stated in a comment to the question by Loong, the preferred IUPAC name according to the 2013 nomenclature recommendations is:
3-(10,11-dihydro-5H-dibenzo[a,d][7]annulen-5-ylidene)-N,N-dimethylpropan-1-amine
The only change this makes to the analysis it that we can ignore the ‘incorrect’ cycloheptene, because [7]annulen is automatically a cycloheptatriene-type molecule.
First, let’s separate the name into its fragments. We have:
3-something-propane-1-amine
N,N-dimethyl
(10,11-dihydro-something)
(something-5H-dibenzo[a,d]cycloheptene-something)
(something-5-ylidene)
I’m going to start with item 4, since that is the main bicycle. Cycloheptene sounds like this molecule:
But the [a,d] and the dibenzo is telling us that we have a fused polycyclic unsaturated hydrocarbon, so we will need to add two more double bonds. (Skipping a picture of this step.) Dibenzo means that there are two fused benzene rings, and the letters in square brackets symbolise the attachment points. a stands for 1,2; d for 4,5 (analogously for other letters). With that, we get a tricyclic compound with many double bonds. However, it is still ambiguous how exactly to place the double bonds, we need the information 5H — it tells us that the ‘additional’ hydrogen must be at the 5-position. Beware: The 5-position does not reference the initial numbering we used for fusing the rings; the atoms are renumbered according to the rules for aromatic polycycles: Starting at the top right and going clockwise, ignoring all bridgehead atoms. So we get 5H-dibenzo[a,d]cycloheptene which looks like this:
Next up, item 3: 10,11-dihydro. This means that the double bond in the seven-membered ring is hydrated, i.e. there is a single bond instead.
And finally, item 5: 5-ylidene. We are attaching something to carbon 5 via a double bond. We’ll get back to that.
Item 1: 3-something-propane-1-amine. That’s nice and simple, we’ll first consider propane-1-amine:
N,N-dimethyl (item 2) tells us that there are two methyl groups attached to the nitrogen, giving us the following:
And now we need to add the entire tricyclo-blurb to the propane’s 3-position using a double bond:
And voilà, there is amitriptylene!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does 'require: false' in Gemfile mean?
Does this:
gem 'whenever', require: false
mean that the gem needs to be installed, or does it mean it is not required?
A:
This means install the gem, but do not call require when you start Bundler. So you will need to manually call
require "whenever"
if you want to use the library.
If you were to do
gem "whenever", require: "whereever"
then bundler would download the gem named whenever, but would call
require "whereever"
This is often used if the name of library to require is different than the name of the gem.
A:
You use :require => false when you want the gem to be installed but not "required".
So in the example you gave:
gem 'whenever', :require => false
when someone runs bundle install the whenever gem would be installed as with gem install whenever. Whenever is used to create cron jobs by running a rake task but isn't usually used from within the rails (or other framework if not rails) application.
So you can use :require => false for anything that you need to run from the command line but don't need within your code.
A:
require: false tells Bundler.require not to require that specific gem: the gem must be required explicitly via require 'gem'.
This option does not affect:
bundle install: the gem will get installed regardless
the require search path setup by bundler.
Bundler adds things to the path when you do either of:
Bundle.setup
which is called by require bundler/setup
which is called by bundle exec
Example
Gemfile
source 'https://rubygems.org'
gem 'haml'
gem 'faker', require: false
main.rb
# Fail because we haven't done Bundler.require yet.
# bundle exec does not automatically require anything for us,
# it only puts them in the require path.
begin Haml; rescue NameError; else raise; end
begin Faker; rescue NameError; else raise; end
# The Bundler object is automatically required on `bundle exec`.
Bundler.require
Haml
# Not required because of the require: false on the Gemfile.
# THIS is what `require: false` does.
begin Faker; rescue NameError; else raise; end
# Faker is in the path because Bundle.setup is done automatically
# when we use `bundle exec`. This is not affected by `require: false`.
require 'faker'
Faker
Then the following won't raise exceptions:
bundle install --path=.bundle
bundle exec ruby main.rb
On GitHub for you to play with it.
Rails usage
As explained in the initialization tutorial, the default Rails template runs on startup:
config/boot.rb
config/application.rb
config/boot.rb contains:
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
which does the require 'bundler/setup' and sets up the require path.
config/application.rb does:
Bundler.require(:default, Rails.env)
which actually requires the gems.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
RSA decryption in Python how i can get a bytes array?
I am trying to use RSA with Python.
I do encryption from .net with the public key generated in Python. Everything going fine for encryption.
When i decrypt my crypted sentence i am not able to bring back to the right value.
How can i convert back my value to a bytes array ? I am sure i am close ... but did not find nothing
I encrypt this bytes array with my public key, but when i decrypt i am not able to get it back
[0] 3 byte
[1] 180 byte
[2] 214 byte
[3] 196 byte
[4] 37 byte
[5] 120 byte
[6] 213 byte
[7] 71 byte
[8] 143 byte
[9] 64 byte
[10] 168 byte
[11] 245 byte
[12] 172 byte
[13] 178 byte
[14] 120 byte
[15] 114 byte
The public key i used is :
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwsfuJS3TFA5KmzBiFdpS
jl4gBG/oiQcd8JhB2hS2xi/3d/HnyQwzVFbnIuRFWxCSPbbO0M0IC2bE8g0ekWDj
b3YsW7POjVpz6xl/VfcTECIDq0/yGDj5O/FYWx8BGtaPTiTNHq7a5DUUANreYHuB
vzEYyr5lLzsSmZ9pG1BikR0dU5p01g64zJDNtYv6iHvIRseP/2T+Jv44XBLA0eBz
m7Q84dCIX/W8LjV6a6bp4kxBUJ4LYjG2BDslx7ZQMHz7gRFhauNQhyTGXTSLULY+
Q+fhUYhoL+RZjddlO/bn7fG1Evc6TiQi165/ZtfQuCJhkuet4q+Q5jUdUiLTUAfj
gwIDAQAB
-----END PUBLIC KEY-----
My private key is :
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAwsfuJS3TFA5KmzBiFdpSjl4gBG/oiQcd8JhB2hS2xi/3d/Hn
yQwzVFbnIuRFWxCSPbbO0M0IC2bE8g0ekWDjb3YsW7POjVpz6xl/VfcTECIDq0/y
GDj5O/FYWx8BGtaPTiTNHq7a5DUUANreYHuBvzEYyr5lLzsSmZ9pG1BikR0dU5p0
1g64zJDNtYv6iHvIRseP/2T+Jv44XBLA0eBzm7Q84dCIX/W8LjV6a6bp4kxBUJ4L
YjG2BDslx7ZQMHz7gRFhauNQhyTGXTSLULY+Q+fhUYhoL+RZjddlO/bn7fG1Evc6
TiQi165/ZtfQuCJhkuet4q+Q5jUdUiLTUAfjgwIDAQABAoIBAA5hwsS+AHLfp0SU
KvngF+5pJsYNGUdc3ioQo/QdSW2Sxxv1IZ8npnaYwBJEdpaFv7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XTGDEz6ikI258QSCNFUaHwVICws7
598VcG9BkuTt0PJXQaTR1aWBBEBAhQ+iIig093Cb6ZZ/7pYz7WCj
-----END RSA PRIVATE KEY-----
The output i received is :
b"\x02-qf\xcc\xf8\x1c\xdc_bV\xa7\x84o\xc7K2k\xe6\xf0\xd4\x8e\x96\xef9\xbb\xe7%j\xa4h\xd5\xcd\xc1c\x0b\t\x98\x9d\xde\xd9\xe7\xe0druq\x90\xfc\xa5O\xd5\xd4\xb6\xec>\xbb($\x02u^\xb8\xe0\xd2W\x8bzL\x1f\xc0\x05\x1c\xf1\xea7\x99\x06\xd0\xa7ov\xa8A\xc3\x0b\x03\xf9\x1a\xac\x92Gn\xa7\xf0\x93v\xd0\xda\x89)G8\xc2e\xd4\xf5\te\x97\xcf a\x9e\xb5\xeei\xc4\xfci\xcd=/\xd3\xa5\x1fE\x0e\xcf\xaeD\x9fHA\x930\xa9EV\xee\x83\x17f\xe9\xc1\xb4\xc7s\xef%F\xb6!\xb4j\x14\xd4\xf1K\xa3r\x90\xbfI\xfd;\xca>zUcR\x16m\x82\x81iz\xb4C\xed\x1e\xdc\xa9\xfc\x0f\x87\xd7-\xde\x9f(l\x042^e\x84\x15\xb2k\x08\x82@\xd3m\x7f\x95\xabvM\xe6\x88\xb2;_\x0f'\xae\xdbvp\x83\xd6\xba\xc0F\x16\x87\xf1\xf0Y\x1fF~L\x18\x1d\x00\x03\xb4\xd6\xc4%x\xd5G\x8f@\xa8\xf5\xac\xb2xr"
There is my code
I get a CryptoHelper.py
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Util import number
import base64
class CryptoHelper:
PrivateKeySize = 2048
def CreateRSA_CSP(self):
csp = RSA.generate(self.PrivateKeySize)
return csp
def GetRSA_PublicKey(self, csp):
return str(csp.publickey().exportKey(format='PEM'),"utf-8")
def RSAEncrypt(self,publicKEY,byteArray):
csp = RSA.importKey(publicKEY);
encrypted = csp.encrypt(byteArray)
return base64.standard_b64encode(encrypted)
def RSADecrypt(self,csp, byteArray):
return csp.decrypt(byteArray)
That is my HandShakeHelper.py
import json
import requests
import base64
import uuid
from Helpers import CryptoHelper
class HandShakeHelper:
CSP = None
CryptoHelper = None
def __init__(self,serial,endPoint):
self.Serial = serial
self.EndPoint = endPoint
def GenerateHandShakeKey(self):
self.CryptoHelper = CryptoHelper.CryptoHelper()
self.CSP = self.CryptoHelper.CreateRSA_CSP()
self.InitializeHandShake()
def InitializeHandShake(self):
print(str(self.CSP.exportKey(format='PEM'),"utf-8"))
print(self.CryptoHelper.GetRSA_PublicKey(self.CSP))
headers = { "Content-Type" : "application/json" }
args = '{ args : { "Publickey" : "' + self.CryptoHelper.GetRSA_PublicKey(self.CSP) + '", "Serial" : "' + self.Serial + '" }}'
answer = requests.post(url = self.EndPoint +"/InitializeHandShake", headers=headers, data = args)
se_answer_raw = json.loads(answer.text)
se_answer = se_answer_raw["d"]
if(se_answer["Status"]==200):
cryptedBase64HandShakeId = base64.standard_b64decode(se_answer["CryptedHandShakeID"])
decryptedBytes = self.CSP.decrypt(cryptedBase64HandShakeId)
print(decryptedBytes)
The handshakehelper call a webservice. Send the public key to the server, and the server return encrypted with the public key a CryptedToken that I try to decrypt.
That is my Test.py
from Helpers import HandShakeHelper, CryptoHelper
handShake = HandShakeHelper.HandShakeHelper("8047771c-b1b0-408d-91ad-eacbc03ae6ca","http://www.localhost.com/webservice.asmx")
handShake.GenerateHandShakeKey()
The .net part is this
CryptoHelper.EncryptRSAContent(clientPublicKey, MyGuid.ToByteArray(), false)
public static byte[] EncryptRSAContent(string publicKey, byte[] content, bool fOAEP)
{
byte[] cryptedData = null;
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
if (publicKey.StartsWith("<RSAKeyValue>"))
{
RSA.FromXmlString(publicKey);
}
else
{
PEMCrypto.ImportPublicKey(publicKey, RSA);
}
cryptedData = RSA.Encrypt(content, fOAEP);
}
return cryptedData;
}
A:
Thanks to @t.m.adaam it's working fine
I correct my CryptoHelper.py with that version
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto.Util import number
from Crypto import Random
import base64
class CryptoHelper:
PrivateKeySize = 2048
def CreateRSA_CSP(self):
csp = RSA.generate(self.PrivateKeySize)
return csp
def GetRSA_PublicKey(self, csp):
return str(csp.publickey().exportKey(format='PEM'),"utf-8")
def RSAEncrypt(self,publicKEY,byteArray):
csp = RSA.importKey(publicKEY);
rsa_csp = PKCS1_v1_5.new(csp)
return base64.standard_b64encode(rsa_csp.encrypt(byteArray))
def RSADecrypt(self,csp, byteArray):
sentinel = Random.new().read(256)
rsa_csp = PKCS1_v1_5.new(csp)
return rsa_csp.decrypt(byteArray,sentinel)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Converting at least two text files with different rows into one csv - powershell
I am trying to convert two TXT files into one CSV file using powershell script. When files have same structure, and same number of rows then case looks be easy. But in my case txt files have diffrent structure.
Pipe sign in both txt files is not a delimiter should be treat as normal character and it is a string.
File URL.txt
L5020|http://linktosite.de|URL
L100|http://sitelink.de|URL
L50|http://abcde.de|URL
L511|http://bbcccddeee.de|URL
L300|http://link123456.de|URL
L5450|http://randomlink.de|URL_DE
L5460|http://randomwebsitelink.de|URL_DE
File URL1.txt
L5020|http://linktosite.de|URL|P555
L100|http://sitelink.de|URL|P523
L50|http://abcde.de|URL|P53
L511|http://bbcccddeee.de|URL|P540
CSV which I expect should look like as below and delimiter is ";"
HEADER1;HEADER2
L5020|http://linktosite.de|URL;L5020|http://linktosite.de|URL|P555
L100|http://sitelink.de|URL;L100|http://sitelink.de|URL|P523
L50|http://abcde.de|URL;L50|http://abcde.de|URL|P53
L511|http://bbcccddeee.de|URL;L511|http://bbcccddeee.de|URL|P540
L300|http://link123456.de|URL;
L5450|http://randomlink.de|URL_DE;
L5460|http://randomwebsitelink.de|URL_DE;
I tried something like that
$URL = "C:\Users\XXX\Desktop\URL.txt"
$URLcontent = Get-Content $URL
$URL1 = "C:\Users\XXX\Desktop\URL1.txt"
$URLcontent1 = Get-Content $URL1
$results = @() # Empty array to store new created rows in
$csv = Import-CSV "C:\Users\XXX\Desktop\map.csv" -Delimiter ';'
foreach ($row in $csv) {
$properties = [ordered]@{
HEADER1 = $URLcontent
HEADER2 = $URLcontent1
}
# insert the new row as an object into the results-array
$results += New-Object psobject -Property $properties
}
# foreach-loop filled the results-array - export it as a CSV-file
$results | Export-Csv "C:\Users\XXXX\Desktop\map_final.csv" -NoTypeInformation
And something like that:
import-csv URL.txt -Header 'HEADER1' | Export-CSV "C:\Users\xxx\Desktop\URL.csv" -Delimiter ';' -NoTypeInformation
import-csv URL1.txt -Header 'HEADER2' | Export-CSV "C:\Users\xxx\Desktop\URL1.csv" -Delimiter ';' -NoTypeInformation
Get-ChildItem "C:\Users\xx\Desktop" -Filter "URL*.csv" | Select-Object -ExpandProperty FullName | Import-Csv | Export-Csv .\combinedcsvs.csv -NoTypeInformation -Append
Without any succes...
BR
A:
Based on the updates in your question, if you want to build something yourself, you probably want to do something like this:
$Url1 = @(Get-Content .\URL1.txt)
$i = 0
Get-Content .\URL.txt | Foreach-Object {
[pscustomobject]@{
HEADER1 = $_
HEADER2 = If ($i -lt $URL1.Count) { $URL1[$i++] }
}
} | Export-Csv .\combinedcsvs.csv -Delimiter ';' -NoTypeInformation -Append
In case you do not want to go through the hassle of reinventing the wheel (with all pitfalls including performance tuning). Using the Join-Object I mentioned in the comment:
Import-Csv .\URL.txt -Header HEADER1 |
LeftJoin (Import-Csv .\URL1.txt -Header HEADER2) |
Export-Csv .\combinedcsvs.csv -Delimiter ';' -NoTypeInformation -Append
Note1: I am not sure why you trying to import anything like map.csv, I think that is required.
Note2: If you still want to go your own way, try to avoid using the increase assignment operator (+=) to create a collection it is a very expensive operator.
Note3: it is generally not a good idea to join lines on their line index as the list might not be sorted or have duplicates, therefore it is better to join lists on a specific property, like the the Url:
Import-Csv .\URL.txt -Delimiter '|' -Header Lid,Url,Type |
LeftJoin (Import-Csv .\URL1.txt -Delimiter '|' -Header Lid2,Url,Type2,Pid) -On Url |
Format-Table # or: Export-Csv .\combinedcsvs.csv -Delimiter ';' -NoTypeInformation
Lid Url Type Lid2 Type2 Pid
--- --- ---- ---- ----- ---
L5020 http://linktosite.de URL L5020 URL P555
L100 http://sitelink.de URL L100 URL P523
L50 http://abcde.de URL L50 URL P53
L511 http://bbcccddeee.de URL L511 URL P540
L300 http://link123456.de URL
L5450 http://randomlink.de URL_DE
L5460 http://randomwebsitelink.de URL_DE
Or on all three (Lid, Url and Type) properties:
Import-Csv .\URL.txt -Delimiter '|' -Header Lid,Url,Type |
LeftJoin (Import-Csv .\URL1.txt -Delimiter '|' -Header Lid,Url,Type,Pid) -On Lid,Url,Type |
Format-Table # or: Export-Csv .\combinedcsvs.csv -Delimiter ';' -NoTypeInformation
Lid Url Type Pid
--- --- ---- ---
L5020 http://linktosite.de URL P555
L100 http://sitelink.de URL P523
L50 http://abcde.de URL P53
L511 http://bbcccddeee.de URL P540
L300 http://link123456.de URL
L5450 http://randomlink.de URL_DE
L5460 http://randomwebsitelink.de URL_DE
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mysql Forcing close of thread 946 user
My mysql box keeping shutting down and up. Below is snippet of the log file. There is quite a number of places I notice this Forcing close of thread 946 user:
130426 12:36:28 [Note] Event Scheduler: Purging the queue. 0 events
130426 12:36:28 InnoDB: Starting shutdown...
130426 12:36:31 InnoDB: Shutdown completed; log sequence number 0 1111309
130426 12:36:31 [Note] /usr/libexec/mysqld: Shutdown complete
130426 12:36:31 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
130426 12:36:32 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
130426 12:36:32 InnoDB: Initializing buffer pool, size = 8.0M
130426 12:36:32 InnoDB: Completed initialization of buffer pool
130426 12:36:32 InnoDB: Started; log sequence number 0 1111309
130426 12:36:32 [Note] Event Scheduler: Loaded 0 events
130426 12:36:32 [Note] /usr/libexec/mysqld: ready for connections.
Version: '5.1.67' socket: '/var/lib/mysql/mysql.sock' port: 3306 Source distribution
130426 21:05:19 [Note] /usr/libexec/mysqld: Normal shutdown
130426 21:05:19 [Note] Event Scheduler: Purging the queue. 0 events
130426 21:05:21 [Warning] /usr/libexec/mysqld: Forcing close of thread 946 user: ''
130426 21:05:22 InnoDB: Starting shutdown...
130426 21:05:23 InnoDB: Shutdown completed; log sequence number 0 1111309
130426 21:05:23 [Note] /usr/libexec/mysqld: Shutdown complete
130426 21:05:23 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
130426 21:05:25 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
130426 21:05:25 InnoDB: Initializing buffer pool, size = 8.0M
130426 21:05:25 InnoDB: Completed initialization of buffer pool
130426 21:05:25 InnoDB: Started; log sequence number 0 1111309
130426 21:05:25 [Note] Event Scheduler: Loaded 0 events
130426 21:05:25 [Note] /usr/libexec/mysqld: ready for connections.
Version: '5.1.67' socket: '/var/lib/mysql/mysql.sock' port: 3306 Source distribution
130428 0:47:12 [Note] /usr/libexec/mysqld: Normal shutdown
130428 0:47:12 [Note] Event Scheduler: Purging the queue. 0 events
130428 0:47:12 InnoDB: Starting shutdown...
130428 0:47:16 InnoDB: Shutdown completed; log sequence number 0 1111309
130428 0:47:16 [Note] /usr/libexec/mysqld: Shutdown complete
A:
This seems to be one of those errors that won't go away. In this case, it may be a case of human error.
First of all, here are a series of links with similar error messages on Shutdowns
http://www.webhostingtalk.com/showthread.php?t=518682
http://bugs.mysql.com/bug.php?id=7403
http://bugs.mysql.com/bug.php?id=48879
http://lists.mysql.com/mysql/206094
http://dev.mysql.com/doc/refman/5.6/en/error-log.html (See User Comments)
http://www.mail-archive.com/mysql@lists.mysql.com/msg12324.html
They all have seem to have one thing in common: MySQL for Windows.
It was claimed that Bug 7403 (the second link) was fixed and patch implemented July 14, 2005: http://lists.mysql.com/internals/27091
The versions of MySQL that this fix should be in 4.0, 5.0.40, 5.1.42. Looking in the error log you posted, I see you are using MySQL 5.1.67. Apparently, no one knows how to fix this issue or wants to (http://bugs.mysql.com/bug.php?id=7403) I also noted that the error messages indicate that you are using MySQL in Linux already.
I have three(3) suggestions that range from the most passive to the most aggressive...
SUGGESTION #1
Try setting log_warnings to 0, if you don't mind flying blind on warnings.
SUGGESTION #2
Upgrade to MySQL 5.6.11. Hopefully, there is should be more updates and bug fixes for this.
SUGGESTION #3
Move the Database to Linux. There should be more stability for this problem away on a better machine with the most updated kernel for the OS.
Give it a Try !!!
UPDATE 2013-04-30 11:20 EDT
Here is the fastest way to check for table corruption
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Line joins not covering (miter)
I have the following code of a voltage source connected to two resistors.
\documentclass{standalone}
\usepackage{tikz}
\usepackage{circuitikz}
\begin{document}
\begin{circuitikz}[line width=1pt]
\draw[line join=miter] (0,0) to[V=$U$] ++(0,2) to[R=$R_i$, -*] ++(2,0) to[short, i=$I$] ++(1,0) to[R=$R_u$] ++(0,-2) to[short, -*] ++(-1,0) to[short] (0,0);
\end{circuitikz}
\end{document}
which creates the following schematics.
As you can see, the beginpoint and endpoint (lower left corner) do not connect properly. I tried to use line join=miter but with no succes. How to do it properly?
A:
Here are a couple more variants:
\documentclass[multi=circuitikz]{standalone}
\usepackage{circuitikz}
\begin{document}
\begin{circuitikz}[line width=1pt]
\draw[line join=miter] (0,0) to[V=$U$,name=U] ++(0,2)
to[R=$R_i$, -*] ++(2,0)
to[short, i=$I$] ++(1,0)
to[R=$R_u$] ++(0,-2)
to[short, -*] ++(-1,0)
to[short] (0,0)
to[short] (U.west);
\end{circuitikz}
\begin{circuitikz}[line width=1pt]
\draw[line join=miter] (2,0) to[short,*-] (0,0)
to[V=$U$] ++(0,2)
to[R=$R_i$, -*] ++(2,0)
to[short, i=$I$] ++(1,0)
to[R=$R_u$] ++(0,-2)
to[short,-*] (2,0);
\end{circuitikz}
\end{document}
A:
My first reaction was to tell you to use cycle but this does not work, as mentioned in section 5.10 of the circuitikz manual. The reason is, as explained a bit more below, that the path gets decomposed into subpaths such that you need to add -.. In situations in which the path does not get divided into subpaths, you should use cycle, but this does not work here, so you need to "help" TikZ doing the right thing.
\documentclass{standalone}
\usepackage{tikz}
\usepackage{circuitikz}
\begin{document}
\begin{circuitikz}[line width=1pt]
\draw[line join=miter] (0,0) to[V=$U$] ++(0,2) to[R=$R_i$, -*] ++(2,0)
to[short, i=$I$] ++(1,0) to[R=$R_u$] ++(0,-2) to[short, -*] ++(-1,0)
to[short,-.] (0,0);
\end{circuitikz}
\end{document}
NOTE ADDED: As this has lead to some confusion, I'd like to add some information. The obvious puzzle is why cycle doesn't work. This is because he behavior of to changes in circuitikz when one uses certain keys. Consider the MWE
\documentclass[border=3.14mm]{standalone}
\usepackage{tikz}
\usepackage{circuitikz}
\begin{document}
\begin{tikzpicture}[line width=1pt]
\draw[line join=miter] (0,0) to[->] ++(0,2) to ++(2,0) -- cycle;
\end{tikzpicture}
\begin{circuitikz}[line width=1pt]
\draw[line join=miter] (0,0) to[-*] ++(0,2) to ++(2,0) -- cycle;
\end{circuitikz}
\begin{circuitikz}[line width=1pt]
\draw[line join=miter] (0,0) to[short,-*] ++(0,2) to ++(2,0) -- cycle;
\end{circuitikz}
\end{document}
As you can see, the cycle key "does not work" in the last example. On the other hand, the arrow directives -> in the first two examples had no effect. This is because to in connection with short (or other circuitikz directives) decomposed the path. To understand these things better, you may want to look through pgfcircpath.tex, where some of the definitions are made. (Comment: one also finds there
\ifx\pgf@temp\pgf@circ@temp % if it has not a name
\pgfmathrandominteger{\pgf@circ@rand}{1000}{9999}
\ctikzset{bipole/name = #2\pgf@circ@rand} % create it
\fi
I guess that at a given point someone may report some strange behavior because accidentally a wrong path got referenced, but perhaps I am missing something here.) In the vicinity of this block you'll find the path decomposition routines. Altogether, the simplest fix is to look at section 5.10 of the circuitikz manual, where it is suggested to use -., to use what @Kpym suggested, or some of the tricks in John Kormylo's answer (the ordering is random and I am not ranking one proposal over another here).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ASP MVC 3.0 Complex View
I am developing a application for Sales Order Management using ASP.NET MVC 3.0. I need to develop a page where Customer Details can be added.
Customer Details Include
public class Customer
{
public int ID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Alias { get; set; }
public int DefaultCreditPeriod { get; set; }
public Accounts Accounts { get; set; }
public IList<Address> Addresses { get; set; }
public IList<Contact> Contacts { get; set; }
}
public class Accounts
{
public int ID { get; set; }
public string VATNo { get; set; }
public string CSTNo { get; set; }
public string PANNo { get; set; }
public string TANNo { get; set; }
public string ECCNo { get; set; }
public string ExciseNo { get; set; }
public string ServiceTaxNo { get; set; }
public bool IsServiceTaxApplicable { get; set; }
public bool IsTDSDeductable { get; set; }
public bool IsTCSApplicable { get; set; }
}
public class Address
{
public int ID { get; set; }
public AddressType Type { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string Line4 { get; set; }
public string Country { get; set; }
public string PostCode { get; set; }
}
public class Contact
{
public int ID { get; set; }
public ContactType Type { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string PhoneNumber { get; set; }
public string Extension { get; set; }
public string MobileNumber { get; set; }
public string EmailId { get; set; }
public string FaxNumber { get; set; }
public string Website { get; set; }
}
Customer Requires a single page to fill all the customer details(General info, Account Info,Address Info and Contact Info). There will be multiple Addresses(Billing, Shipping, etc) and multiple Contacts (Sales, Purchase). I am new to MVC. How to Create the View for the above and Add multiple Address dynamically?
A:
I often create wrapper models to handle this kind of situation e.g.
public class CustomerWrapperModel
{
public Customer Customer { get; set;}
public Accounts Accounts { get; set;}
public List<Address> AddressList { get; set}
//Add
public CustomerWrapperModel()
{
}
//Add/Edit
public CustomerWrapperModel(Customer customer, Accounts accounts, List<Address> addressList)
{
this.Customer = customer;
this.Accounts = accounts;
this.AddressList = addressList;
}
}
then declare the View to be of type CustomerWrapperModel and use editors like so:
@model MyNamespace.CustomerWrapperModel
@Html.EditorFor(model => model.Customer)
@Html.EditorFor(model => model.Accounts)
@Html.EditorFor(model => model.AddressList)
and have a controller to receive the post that looks like this:
[HttpPost]
public ActionResult(Customer customer, Accounts accounts, List<Address> addressList)
{
//Handle db stuff here
}
As far as adding addresses dynamically I found the best way to do this if you're using MVC validation and want to keep the list structured correctly with the right list indexes so that you can have the List parameter in your controller is to post the current Addresses to a helper controller like this:
[HttpPost]
public PartialResult AddAddress(List<Address> addressList)
{
addressList.Add(new Address);
return PartialView(addressList);
}
then have a partial view that just renders out the address fields again:
@model List<MyNamespace.Address>
@{
//Hack to get validation on form fields
ViewContext.FormContext = new FormContext();
}
@Html.EditorForModel()
make sure you address fields are all in one container and then you can just overwrite the existing ones with the returned data and your new address fields will be appended at the bottom. Once you have updated your container you can do something like this to rewire the validation:
var data = $("form").serialize();
$.post("/Customer/AddAddress", data, function (data) {
$("#address-container").html(data);
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
});
NB. I know some people with have an issue with doing it this way as it requires a server side hit to add fields to a page that could easily just be added client side (I always used to do it all client side but tried it once with this method and have never gone back). The reason I do it this way is because it's the easiest way to keep the indexes on the list items correct especially if you have inserts as well as add and your objects have a lot of properties. Also, by using the partial view to render the data you can ensure that the validation is generated on the new fields for you out of the box instead of having to hand carve the validation for the newly added client side fields. The trade off is in most cases a minor amount of data being transferred during the ajax request.
You may also choose to be more refined with the fields you send to the AddAddress controller, as you can see I just post the entire form to the controller and ignore everything but the Address fields, I am using fast servers and the additional (minor) overhead of the unwanted form fields is negligible compared to the time I could waste coding this type of functionality in a more bandwidth efficient manner.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
March Movie Event!! - Starship Troopers - March 18th at 11pm GMT (7pm EDT)
Movie Night seems to have been a bit quiet recently, so to get things going again I'm nominating the single finest science fiction film ever made as our March Movie night film. That's right people, we're watching Starship Troopers! All are welcome to join in on March 18th at 11pm GMT (7pm EDT)
The more people that come to the chatroom, the merrier it'll be and remember,
"Service guarantees citizenship!"
FAQ
What is a movie night?
Which version will we be watching? The theatrical cut is currently available on Youtube here and here. There are also copies available on DailyMotion, Amazon Prime and Hulu. Amazon Prime members with the STARZ channel can watch it free, or use the STARZ channel 2-week free trial to watch it free.
What if I want to complain loudly about the film being worse than the book? Then prepare to be pelted with popcorn!
I'm doing my part!
A:
Movie night was a great success
We had six active participants (The Dark Lord - First time contributor, MissMonicaE - First time contributor, Kyle Jones, Edlothiad - First time contributor and Himarm). That number goes up to seven if you include CreationEdge who joined us a few minutes after the film ended to say
Oh I missed the movie?
We also had no less than 9 lurkers which brings the grand total to nearly 15 viewers!
Funniest comment goes to MissMonicaE for
Is there really this much public kissing in high school? I'm so glad I
was homeschooled
and The Dark Lord for
Time since last incident: 0 days.
The winner of the 'Captain Obvious' prize goes to Himarm for
shower scene is always fun
and MissMonicaE for
Ladies love a man in uniform
Honourable mention goes to Edlothiad for
Lieutenant Dan?! oh wrong film
What did we learn?
This film was chosen by diktat rather than a democratic vote on Meta.
Historically there seems to be little benefit in allowing the community to choose over simply announcing what film is being shown.
The post was "featured" early (with the date, time and movie name in the title).
Placing it on the main board seems to have attracted no less than six users who've never come into chat before, one of whom then contributed to the event. The vote-count seem to have largely reflected the number of participants.
Making it a featured event in chat seems to have had little impact.
Only two people "registered" for the event.
Picking a film that was accessible online seems to have been a benefit.
At least three of the contributors were watching a version that was streaming from youtube rather than having to download their own copy.
The date and time seem amenable (to most)
Placing it on a weekend evening appears to have been more effective than making it mid-week, something we tried last year with very limited success.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Drilling holes in concrete
I'm not what you'd call a handy guy, and now wife wants me to put up curtains. This task is reduced primarily to getting a bit of metal stuck to the ceiling.
I bought screws and anchors. The anchors are a bit shorter than the screws. The clerk in the store told me that's normal. After some soul searching, I managed to drill the holes as deep as the screws. At first, I was worried that the holes were too big, since I can put the plastic anchors in with my finger.
When I try screwing in the screw, I'm physically unable to turn the screwdriver about halfway in (at this point I'm unable to yank it out of the hole either, so I'm assuming that the plastic bit expands on the inside). I don't have one of those screw-driving thingies, but I attached a screwdriver instead of the drillbit on the drill I used to make the hole, and it just "jumps out" every time I press the trigger.
I'm confused. The only possibilities that I can see are as follows:
I am not strong enough and the drill is in high gear so it can't be used this way.
Somehow I managed to mix up the anchors and the screws.
Well, here are the culprits:
Oh, don't worry about the hole in the background. That one hit something shiny, so I abandoned it. Anyway, that's about as far as I can screw it the screw without losing my cool. Oh, it's my ceiling btw.
A:
No, this isn't normal. Your anchors don't fit to your screws. What is happening is that the tip of the screw reached the concrete, and, of course, you can't force a screw into concrete - not even with a drill or a electric screwdriver, and certainly not by hand.
This picture shows how anchor and screw should fit into the hole. The hole definitely needs to be longer than the screw. The screw should be a bit longer than the anchor, but not as long. Maybe the clerk saw that you have picked an wood screw and gave you anchors suited for the second situation. It doesn't hurt to use wood screws with anchors in a concrete wall, you'll just have the cap jutting out a bit. But the length of the screw should be only a bit longer than that of the anchor (the surplus should equal the length of the tip + the length of the attached thing), and your cap will stick out a bit if the thing you are attaching isn't soft enough for the cap to sink in.
The table shows how to determine the correct hole depth. It also tells you what diameter of anchor and drill to choose for a given screw. As for the length of the screw, it is determined by the weight it will have to carry. Vertical screws are more problematic than screws in walls, because gravity is pulling in the direction of the hole, not at 90° to it. Light curtains will be OK with your size screw, but don't put any molton on them.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to say that the "geometry is the same" at every point of a metric space?
In physics, homogenous is used to mean that some quantity does not change with position.
This is less general than the use of homogeneous in mathematics, I think.
Question: So how does one define a metric space which is "homogeneous" in the sense of physics, i.e. its (metric) geometry is the same at every point?
(E.g. hyperbolic, Euclidean, and spherical geometries.)
There are definitions of a homogeneous metric space (see here or here), but both seem to be more general than what I am trying to describe above.
Attempt: Given a metric space $(X,d)$, denote the isometry group by $Iso(X)$, and for each $x \in X$, denote the subgroup of $Iso(X)$ consisting of elements fixing $x$ ($f(x) = x, f \in Iso(X)$), by $Iso(X,x)$.
Then a metric space "has the same geometry at each point" if and only if, for any two points $x_1, x_2 \in X$, one has that $Iso(X,x_1) \cong Iso(X, x_2)$.
Euclidean space satisfies this condition, since $Iso(X,x) \cong O(n)$ for any point $x$ in $n$-dimensional Euclidean space (I think). I don't know if hyperbolic and spherical geometries satisfy this too.
A:
The definition of a homogeneous metric space is a little stronger than what you say: a metric space $(X,d)$ is homogeneous if and only if for every $x_1,x_2 \in X$ there exists $f \in Iso(X)$ such that $f(x_1)=x_2$. This implies the identity that you asked for, namely that $Iso(X,x_1) \simeq Iso(X,x_2)$, because one obtains an isomorphism
$$A : Iso(X,x_1) \to Iso(X,x_2)
$$
using the "conjugation" formula, also called the "adjoint" formula
$$A(g) = f \circ g \circ f^{-1} \in Iso(X,x_2) \quad\text{for each}\quad g \in Iso(X,x_1)
$$
All the geometries that you mention --- spherical, Euclidean, and hyperbolic --- are homogenous in this stronger sense: one simply works in Euclidean geometry, in spherical geometry, or in some particular model of hyperbolic geometry, to directly construct a desired isometry taking any given point $x_1$ to any other given point $x_2$. Those geometries therefore all satisfy the identity that you ask for, namely $Iso(X,x) \simeq O(n)$ for each $x \in X$, because you can easily use the symmetry of the metric to verify this identity for one particular value of $x$: use the origin in Euclidean space; the north pole in spherical space with the metric expressed in spherical coordinates; or the center of the Poincare disc model of hyperbolic space.
|
{
"pile_set_name": "StackExchange"
}
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 5