qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
19,048,384
I have found the following code(see below link) to copy and execute the commands on remote windows machine. I could able to run all the windows commands but When I give C:\file.exe as the input windows command line is not executing my command. Can I execute file in remote machine like this or is any other pythonic way of doing this? Please help...Thanks In advance <http://code.activestate.com/recipes/577945-execute-remote-commands-on-windows-like-psexec/>
2013/09/27
[ "https://Stackoverflow.com/questions/19048384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2670216/" ]
<http://opencobol.add1tocobol.com/#what-are-the-xf4-xf5-and-x91-routines> The CALL's X"F4", X"F5", X"91" are from MF. You can find them in the online MF doc under Library Routines. F4/F5 are for packing/unpacking bits from/to bytes. 91 is a multi-use call. Implemented are the subfunctions get/set cobol switches (11, 12) and get number of call params (16). Use ``` CALL X"F4" USING BYTE-VAR ARRAY-VAR RETURNING STATUS-VAR ``` to pack the last bit of each byte in the 8 byte ARRAY-VAR into corresponding bits of the 1 byte BYTE-VAR. The X”F5” routine takes the eight bits of byte and moves them to the corresponding occurrence within array. X”91” is a multi-function routine. ``` CALL X"91" USING RESULT-VAR FUNCTION-NUM PARAMETER-VAR RETURNING STATUS-VAR ``` As mentioned by Roger, OpenCOBOL supports FUNCTION-NUM of 11, 12 and 16. 11 and 12 get and set the on off status of the 8 (eight) run-time OpenCOBOL switches definable in the SPECIAL-NAMES paragraph. 16 returns the number of call parameters given to the current module.
`x'91'` is a general library routine, for a complete list of those see the [MF documentation](https://www.microfocus.com/documentation/visual-cobol/VC22/EclWin/HRCLRHCALL17.html). This documentation also specifies what its [function 11](https://www.microfocus.com/documentation/visual-cobol/VC22/EclWin/HRCLRHCALL6E.html) and [function 12](https://www.microfocus.com/documentation/visual-cobol/VC22/EclWin/HRCLRHCALL6F.html) do: they set/read the [COBOL runtime switches](https://www.microfocus.com/documentation/visual-cobol/VC22/EclWin/HRRTRHRTSW01.html) [0-7](https://www.microfocus.com/documentation/visual-cobol/VC22/EclWin/HRRTRHRTSW06.html) and the internal debugging mode switch. Other than these library routines you can also [read them one by one](https://www.microfocus.com/documentation/visual-cobol/VC22/EclWin/) from COBOL and set "some" switches via the [`SET` statement](https://www.microfocus.com/documentation/visual-cobol/VC22/EclWin/HRLHLHPDFC03.html).
102,549
I am trying to solve this equation using the series $$\sum\_0^\infty a\_nx^n$$ $$y'' - xy'+(3x-2)y=0$$ How to do that? I mean that I can replace the variables using the series but then I cannot add this thing cause the limits of the sums are not the same. Maybe I am doing something wrong here. I tried to make all sums start from $0$ with $x^{n+1}%$. This will leave $2a\_2 - 2a\_0 + \sum\dots = 0$ and I don't know what to do. I can't just say that $2a\_2 = 2a\_0 = 0$ cause it may be $2a\_2 - 2a\_0 = 0$. Well I am really confused.
2012/01/26
[ "https://math.stackexchange.com/questions/102549", "https://math.stackexchange.com", "https://math.stackexchange.com/users/22968/" ]
Assuming the length is fixed, you can just interleave the bits of the numbers. For example, if the vector is $(1,2,3)$ we have $1 = 01\_2$, $2=10\_2$, $3=11\_2$, so the result is $53 = 110101\_2$. The first bit of $53$ is the first bit of $1$, the second bit is the first bit of $2$, ..., the sixth bit of $53$ is the second bit of $3$. This works essentially the same way if the values are real. A similar construction is used to prove the cardinal equation $^2$ = . To encode a 3-vector this way in C: ``` #include <stdio.h> #include <stdint.h> uint32_t zip(uint8_t a, uint8_t b, uint8_t c) { int i; uint32_t d = 0; for (i = 0; i < 8; ++i) { d |= (a & (1 << i)) << (0 + (i << 1)); d |= (b & (1 << i)) << (1 + (i << 1)); d |= (c & (1 << i)) << (2 + (i << 1)); } return d; } int main(int argc, char **argv) { printf("%u\n", zip(1, 2, 3)); return 0; } ```
You could use an adaptation of Cantor's method of [counting the rational numbers](http://kaumad.blogspot.com/). Take a two-dimensional vector instead of the rational numbers, include the numbers with alternating sign to get the negatives and you are there. For higher dimension, you could use the same method rescursively.
102,549
I am trying to solve this equation using the series $$\sum\_0^\infty a\_nx^n$$ $$y'' - xy'+(3x-2)y=0$$ How to do that? I mean that I can replace the variables using the series but then I cannot add this thing cause the limits of the sums are not the same. Maybe I am doing something wrong here. I tried to make all sums start from $0$ with $x^{n+1}%$. This will leave $2a\_2 - 2a\_0 + \sum\dots = 0$ and I don't know what to do. I can't just say that $2a\_2 = 2a\_0 = 0$ cause it may be $2a\_2 - 2a\_0 = 0$. Well I am really confused.
2012/01/26
[ "https://math.stackexchange.com/questions/102549", "https://math.stackexchange.com", "https://math.stackexchange.com/users/22968/" ]
Assuming the length is fixed, you can just interleave the bits of the numbers. For example, if the vector is $(1,2,3)$ we have $1 = 01\_2$, $2=10\_2$, $3=11\_2$, so the result is $53 = 110101\_2$. The first bit of $53$ is the first bit of $1$, the second bit is the first bit of $2$, ..., the sixth bit of $53$ is the second bit of $3$. This works essentially the same way if the values are real. A similar construction is used to prove the cardinal equation $^2$ = . To encode a 3-vector this way in C: ``` #include <stdio.h> #include <stdint.h> uint32_t zip(uint8_t a, uint8_t b, uint8_t c) { int i; uint32_t d = 0; for (i = 0; i < 8; ++i) { d |= (a & (1 << i)) << (0 + (i << 1)); d |= (b & (1 << i)) << (1 + (i << 1)); d |= (c & (1 << i)) << (2 + (i << 1)); } return d; } int main(int argc, char **argv) { printf("%u\n", zip(1, 2, 3)); return 0; } ```
If the vector contains fixed-length integers, then you can compute a digest for it, say using MD5, SHA1, SHA2, etc. This is certainly not bijective (because it's not injective) but is unlikely that there'll any be collisions.
102,549
I am trying to solve this equation using the series $$\sum\_0^\infty a\_nx^n$$ $$y'' - xy'+(3x-2)y=0$$ How to do that? I mean that I can replace the variables using the series but then I cannot add this thing cause the limits of the sums are not the same. Maybe I am doing something wrong here. I tried to make all sums start from $0$ with $x^{n+1}%$. This will leave $2a\_2 - 2a\_0 + \sum\dots = 0$ and I don't know what to do. I can't just say that $2a\_2 = 2a\_0 = 0$ cause it may be $2a\_2 - 2a\_0 = 0$. Well I am really confused.
2012/01/26
[ "https://math.stackexchange.com/questions/102549", "https://math.stackexchange.com", "https://math.stackexchange.com/users/22968/" ]
Assuming the length is fixed, you can just interleave the bits of the numbers. For example, if the vector is $(1,2,3)$ we have $1 = 01\_2$, $2=10\_2$, $3=11\_2$, so the result is $53 = 110101\_2$. The first bit of $53$ is the first bit of $1$, the second bit is the first bit of $2$, ..., the sixth bit of $53$ is the second bit of $3$. This works essentially the same way if the values are real. A similar construction is used to prove the cardinal equation $^2$ = . To encode a 3-vector this way in C: ``` #include <stdio.h> #include <stdint.h> uint32_t zip(uint8_t a, uint8_t b, uint8_t c) { int i; uint32_t d = 0; for (i = 0; i < 8; ++i) { d |= (a & (1 << i)) << (0 + (i << 1)); d |= (b & (1 << i)) << (1 + (i << 1)); d |= (c & (1 << i)) << (2 + (i << 1)); } return d; } int main(int argc, char **argv) { printf("%u\n", zip(1, 2, 3)); return 0; } ```
Actually there is an easy way to map a vector of integers to a single integer in a bijective way. First treat numbers as strings say 0 1 00 01 10 11 .. for 0,1,2,3,4,5, ... then bijectively combine the strings a pair at a time using a method like <http://bijective.dogma.net/compres8.htm> The method on that page is for bytes but its easy to make it work for bits. If you can't see how to do that you and change bijectively each string to bytes. example so you want to map a vector or three integers to a single integer. Using method from that page. convert to a strings each of the three integers and then convert to bytes. DSC adds bijectively a number from 0 to N-1 to any file bijectively. For first nunber let it be ZERO then when you add the second number which you have as bytes you use N from the length of previous result it has to be at least one since its non zero. Then for third integer you combine as previous where N is the length of previous result. Its that easy. know that you have this final file you can bijectively convert to string and then that string to a number.
102,549
I am trying to solve this equation using the series $$\sum\_0^\infty a\_nx^n$$ $$y'' - xy'+(3x-2)y=0$$ How to do that? I mean that I can replace the variables using the series but then I cannot add this thing cause the limits of the sums are not the same. Maybe I am doing something wrong here. I tried to make all sums start from $0$ with $x^{n+1}%$. This will leave $2a\_2 - 2a\_0 + \sum\dots = 0$ and I don't know what to do. I can't just say that $2a\_2 = 2a\_0 = 0$ cause it may be $2a\_2 - 2a\_0 = 0$. Well I am really confused.
2012/01/26
[ "https://math.stackexchange.com/questions/102549", "https://math.stackexchange.com", "https://math.stackexchange.com/users/22968/" ]
Here's something that almost works: map the integer vector $(a\_1,a\_2,\dots,a\_n)$ to the (rational) number $2^{a\_1}3^{a\_2}\times\cdots\times p\_n^{a\_n}$, where the numbers $2,3,\dots,p\_n$ are the first $n$ primes. The Unique Factorization Theorem almost guarantees that no two distinct vectors go to the same number. The problem is with zeros: $(-5,6,0)$ and $(-5,6)$ both go to $729/32$. We can fix it by letting $f$ be any 1-1 map from the integers to the nonzero integers, for example, $f(x)=x+1$ if $x\ge0$, $f(x)=x$ if $x\lt0$, and then map $(a\_1,a\_2,\dots,a\_n)$ to $2^{f(a\_1)}3^{f(a\_2)}\times\cdots\times p\_n^{f(a\_n)}$. This map answers the question. EDIT: After I posted what's above, OP commented elsewhere that the image is to be an integer. This can be achieved by letting $f$ be any 1-1 map from the integers to the positive integers, for example, $f(n)=2n$ if $n\gt0$, $f(n)=1-2n$ if $n\le0$. Now $(-5,6,0)$ maps to $2^{11}3^{12}5$, and $(-5,6)$ maps to $2^{11}3^{12}$. The map is not quite a bijection, e.g., nothing maps to $3$.
You could use an adaptation of Cantor's method of [counting the rational numbers](http://kaumad.blogspot.com/). Take a two-dimensional vector instead of the rational numbers, include the numbers with alternating sign to get the negatives and you are there. For higher dimension, you could use the same method rescursively.
102,549
I am trying to solve this equation using the series $$\sum\_0^\infty a\_nx^n$$ $$y'' - xy'+(3x-2)y=0$$ How to do that? I mean that I can replace the variables using the series but then I cannot add this thing cause the limits of the sums are not the same. Maybe I am doing something wrong here. I tried to make all sums start from $0$ with $x^{n+1}%$. This will leave $2a\_2 - 2a\_0 + \sum\dots = 0$ and I don't know what to do. I can't just say that $2a\_2 = 2a\_0 = 0$ cause it may be $2a\_2 - 2a\_0 = 0$. Well I am really confused.
2012/01/26
[ "https://math.stackexchange.com/questions/102549", "https://math.stackexchange.com", "https://math.stackexchange.com/users/22968/" ]
You could use an adaptation of Cantor's method of [counting the rational numbers](http://kaumad.blogspot.com/). Take a two-dimensional vector instead of the rational numbers, include the numbers with alternating sign to get the negatives and you are there. For higher dimension, you could use the same method rescursively.
Actually there is an easy way to map a vector of integers to a single integer in a bijective way. First treat numbers as strings say 0 1 00 01 10 11 .. for 0,1,2,3,4,5, ... then bijectively combine the strings a pair at a time using a method like <http://bijective.dogma.net/compres8.htm> The method on that page is for bytes but its easy to make it work for bits. If you can't see how to do that you and change bijectively each string to bytes. example so you want to map a vector or three integers to a single integer. Using method from that page. convert to a strings each of the three integers and then convert to bytes. DSC adds bijectively a number from 0 to N-1 to any file bijectively. For first nunber let it be ZERO then when you add the second number which you have as bytes you use N from the length of previous result it has to be at least one since its non zero. Then for third integer you combine as previous where N is the length of previous result. Its that easy. know that you have this final file you can bijectively convert to string and then that string to a number.
102,549
I am trying to solve this equation using the series $$\sum\_0^\infty a\_nx^n$$ $$y'' - xy'+(3x-2)y=0$$ How to do that? I mean that I can replace the variables using the series but then I cannot add this thing cause the limits of the sums are not the same. Maybe I am doing something wrong here. I tried to make all sums start from $0$ with $x^{n+1}%$. This will leave $2a\_2 - 2a\_0 + \sum\dots = 0$ and I don't know what to do. I can't just say that $2a\_2 = 2a\_0 = 0$ cause it may be $2a\_2 - 2a\_0 = 0$. Well I am really confused.
2012/01/26
[ "https://math.stackexchange.com/questions/102549", "https://math.stackexchange.com", "https://math.stackexchange.com/users/22968/" ]
Here's something that almost works: map the integer vector $(a\_1,a\_2,\dots,a\_n)$ to the (rational) number $2^{a\_1}3^{a\_2}\times\cdots\times p\_n^{a\_n}$, where the numbers $2,3,\dots,p\_n$ are the first $n$ primes. The Unique Factorization Theorem almost guarantees that no two distinct vectors go to the same number. The problem is with zeros: $(-5,6,0)$ and $(-5,6)$ both go to $729/32$. We can fix it by letting $f$ be any 1-1 map from the integers to the nonzero integers, for example, $f(x)=x+1$ if $x\ge0$, $f(x)=x$ if $x\lt0$, and then map $(a\_1,a\_2,\dots,a\_n)$ to $2^{f(a\_1)}3^{f(a\_2)}\times\cdots\times p\_n^{f(a\_n)}$. This map answers the question. EDIT: After I posted what's above, OP commented elsewhere that the image is to be an integer. This can be achieved by letting $f$ be any 1-1 map from the integers to the positive integers, for example, $f(n)=2n$ if $n\gt0$, $f(n)=1-2n$ if $n\le0$. Now $(-5,6,0)$ maps to $2^{11}3^{12}5$, and $(-5,6)$ maps to $2^{11}3^{12}$. The map is not quite a bijection, e.g., nothing maps to $3$.
If the vector contains fixed-length integers, then you can compute a digest for it, say using MD5, SHA1, SHA2, etc. This is certainly not bijective (because it's not injective) but is unlikely that there'll any be collisions.
102,549
I am trying to solve this equation using the series $$\sum\_0^\infty a\_nx^n$$ $$y'' - xy'+(3x-2)y=0$$ How to do that? I mean that I can replace the variables using the series but then I cannot add this thing cause the limits of the sums are not the same. Maybe I am doing something wrong here. I tried to make all sums start from $0$ with $x^{n+1}%$. This will leave $2a\_2 - 2a\_0 + \sum\dots = 0$ and I don't know what to do. I can't just say that $2a\_2 = 2a\_0 = 0$ cause it may be $2a\_2 - 2a\_0 = 0$. Well I am really confused.
2012/01/26
[ "https://math.stackexchange.com/questions/102549", "https://math.stackexchange.com", "https://math.stackexchange.com/users/22968/" ]
Here's something that almost works: map the integer vector $(a\_1,a\_2,\dots,a\_n)$ to the (rational) number $2^{a\_1}3^{a\_2}\times\cdots\times p\_n^{a\_n}$, where the numbers $2,3,\dots,p\_n$ are the first $n$ primes. The Unique Factorization Theorem almost guarantees that no two distinct vectors go to the same number. The problem is with zeros: $(-5,6,0)$ and $(-5,6)$ both go to $729/32$. We can fix it by letting $f$ be any 1-1 map from the integers to the nonzero integers, for example, $f(x)=x+1$ if $x\ge0$, $f(x)=x$ if $x\lt0$, and then map $(a\_1,a\_2,\dots,a\_n)$ to $2^{f(a\_1)}3^{f(a\_2)}\times\cdots\times p\_n^{f(a\_n)}$. This map answers the question. EDIT: After I posted what's above, OP commented elsewhere that the image is to be an integer. This can be achieved by letting $f$ be any 1-1 map from the integers to the positive integers, for example, $f(n)=2n$ if $n\gt0$, $f(n)=1-2n$ if $n\le0$. Now $(-5,6,0)$ maps to $2^{11}3^{12}5$, and $(-5,6)$ maps to $2^{11}3^{12}$. The map is not quite a bijection, e.g., nothing maps to $3$.
Actually there is an easy way to map a vector of integers to a single integer in a bijective way. First treat numbers as strings say 0 1 00 01 10 11 .. for 0,1,2,3,4,5, ... then bijectively combine the strings a pair at a time using a method like <http://bijective.dogma.net/compres8.htm> The method on that page is for bytes but its easy to make it work for bits. If you can't see how to do that you and change bijectively each string to bytes. example so you want to map a vector or three integers to a single integer. Using method from that page. convert to a strings each of the three integers and then convert to bytes. DSC adds bijectively a number from 0 to N-1 to any file bijectively. For first nunber let it be ZERO then when you add the second number which you have as bytes you use N from the length of previous result it has to be at least one since its non zero. Then for third integer you combine as previous where N is the length of previous result. Its that easy. know that you have this final file you can bijectively convert to string and then that string to a number.
102,549
I am trying to solve this equation using the series $$\sum\_0^\infty a\_nx^n$$ $$y'' - xy'+(3x-2)y=0$$ How to do that? I mean that I can replace the variables using the series but then I cannot add this thing cause the limits of the sums are not the same. Maybe I am doing something wrong here. I tried to make all sums start from $0$ with $x^{n+1}%$. This will leave $2a\_2 - 2a\_0 + \sum\dots = 0$ and I don't know what to do. I can't just say that $2a\_2 = 2a\_0 = 0$ cause it may be $2a\_2 - 2a\_0 = 0$. Well I am really confused.
2012/01/26
[ "https://math.stackexchange.com/questions/102549", "https://math.stackexchange.com", "https://math.stackexchange.com/users/22968/" ]
If the vector contains fixed-length integers, then you can compute a digest for it, say using MD5, SHA1, SHA2, etc. This is certainly not bijective (because it's not injective) but is unlikely that there'll any be collisions.
Actually there is an easy way to map a vector of integers to a single integer in a bijective way. First treat numbers as strings say 0 1 00 01 10 11 .. for 0,1,2,3,4,5, ... then bijectively combine the strings a pair at a time using a method like <http://bijective.dogma.net/compres8.htm> The method on that page is for bytes but its easy to make it work for bits. If you can't see how to do that you and change bijectively each string to bytes. example so you want to map a vector or three integers to a single integer. Using method from that page. convert to a strings each of the three integers and then convert to bytes. DSC adds bijectively a number from 0 to N-1 to any file bijectively. For first nunber let it be ZERO then when you add the second number which you have as bytes you use N from the length of previous result it has to be at least one since its non zero. Then for third integer you combine as previous where N is the length of previous result. Its that easy. know that you have this final file you can bijectively convert to string and then that string to a number.
218,090
What does the following mean? > > They like me for me. > > > I have never seen this expression before.
2019/07/13
[ "https://ell.stackexchange.com/questions/218090", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/98273/" ]
It means people like you the way that you are and they don't want you to change they like the real you like you're not pretending to be something that you're not it's a compliment
(I originally posted this as a comment to the more-recently-asked [What does “like someone for someone” mean?](https://ell.stackexchange.com/questions/253611/what-does-like-someone-for-someone-mean), which was closed as a duplicate.) --- The cited text ***is not idiomatic*** (except insofar as it's "deliberately quirky" because of the way it uses ***me*** twice in proximity with different meanings). People sometimes use reflexive pronouns in such contexts *(I want you to love me for **myself**, Maybe she'll like us for **ourselves**)*, but even that isn't really clear enough. Usually it'll be expressed more explicitly - for example... > > *I want you to love me for **myself, not my wealth*** > > *Maybe she'll like us for **who we are.*** > > >
450,539
``` ubuntu 16.04 LTS $ sudo apt install virtualbox $ virtualbox VirtualBox: supR3HardenedMainGetTrustedMain: dlopen("/usr/lib/virtualbox/VirtualBox.so",) failed: /usr/lib/x86_64-linux-gnu/libQt5OpenGL.so.5: undefined symbol: _ZN6QDebug9putStringEPK5QCharm ``` virtualbox is not run. What's wrong and how can i solve this? ``` $ ls -l /usr/lib/x86_64-linux-gnu/libQt5OpenGL.so.5 lrwxrwxrwx 1 root root 21 5월 13 2017 /usr/lib/x86_64-linux-gnu/libQt5OpenGL.so.5 -> libQt5OpenGL.so.5.5.1 $ apt-cache policy libqt5opengl5 libqt5opengl5: 설치: 5.5.1+dfsg-16ubuntu7.5 후보: 5.5.1+dfsg-16ubuntu7.5 버전 테이블: *** 5.5.1+dfsg-16ubuntu7.5 500 500 http://ftp.daum.net/ubuntu xenial-updates/main amd64 Packages 100 /var/lib/dpkg/status 5.5.1+dfsg-16ubuntu7 500 500 http://ftp.daum.net/ubuntu xenial/main amd64 Packages ```
2018/06/19
[ "https://unix.stackexchange.com/questions/450539", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/279149/" ]
Unfortunately just about the worst thing you can do is to use `rsync` across NFS. (Or to any remote filesystem that's mounted into the local system.) This switches off almost all of the efficiency enhancements for which `rsync` is known. For this much data one of the fastest ways to transfer it between systems may be to dump it across an *unencrypted* connection without any consideration for what was already on the target system. Once you have at least a partial copy the best option is to use `rsync` between the two hosts. This allows `rsync` to run one process on each host to consider and compare differences. (The `rsync` will completely skip files that have the same size and modification date. For other files the client and server components will perform a rolling checksum to determine which block(s) need still to be transferred.) 1. Fast dump. This example uses no authentication or encryption at all. It does apply compression, though, which you can remove by omitting both `-z` flags: Run this on the destination machine to start a listening server: ``` cd /path/to/destination && nc -l 50505 | pax -zrv -pe ``` Run this on the source machine to start the sending client: ``` cd /path/to/source && pax -wz . | nc destination_server 50505 ``` Some versions of `nc -l` may require the port to be specified with a flag, i.e. `nc -l -p 50505`. The OpenBSD version on Debian (`nc.openbsd`, linked via `/etc/alternatives` to `/bin/nc`) does not. 2. Slower transfer. This example uses `rsync` over `ssh`, which provides authentication and encryption. Don't miss off the trailing slash (`/`) on the source path. Omit the `-z` flag if you don't want compression: ``` rsync -avzP /path/to/source/ destination_server:/path/to/destination ``` You may need to set up SSH certificates to allow login to destination\_server as root. Add the `-H` flag if you need to handle hard links.
It is far better to use rsync directly between two hosts if possible. Remember, rsync is built to optimise network IO at the cost of increased disk IO; when using rsync on an NFS filesystem, disk IO translates to network IO, so that is a very suboptimal solution. Also if rsync thinks that both source and destination is local, it will switch off the optimizations and transfer complete files every time, instead of using the differential algorithm that only sends the differences. Say you have a 5GB file that only differs in 1% of the data between source and destination. * When transferring between hosts, rsync will checksum the source and destination files, and only transfer the difference; on the destination the file is recreated using the old file and the new data from the source, and then the old file is replaced. * When transferring locally, it makes no sense to checksum each file, meaning you'd have to read 2 x 5GB and write 1 x 5GB for the example file. By switching to whole file mode, rsync only needs to read 1 x 5GB and write 1 x 5GB. On local disks this makes complete sense, when one is NFS the network bandwidth shoots through the roof. If you can use rsync directly to the host serving the NFS filesystem, then do that, you will see a big improvement in the performance.
65,529,865
This question is similar to: [Does exist application event term in DDD?](https://stackoverflow.com/questions/62054009/does-exist-application-event-term-in-ddd) , but I don't know how to apply the explanations given there to my specific issue. I have a `SearchFilmUseCase` and I want to raise an event `FilmSearchedEvent` once it finishes its execution. Currently, the application layer is raising the event. The only manner in which I could raise this event from the Domain is in the `FilmRepository`. However, the repository is just an interface, so I can't raise any event there. I think that raising the event at the application layer is not correct. How can I approach this situation?
2021/01/01
[ "https://Stackoverflow.com/questions/65529865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2252717/" ]
One solution could be to create a domain service to perform the search and raise the event.
All Domain Events must be raised from domain layer. The best place is an aggregate root where the action should be really done. The aggregate root could contain all the domain events that have been raised, and in the application layer you could get them and publish them to the event bus.
32,253,657
I am trying to filter some row of a table with ssdt (left click on table, view data, sort and filter) Here I simply need to add `IS NULL` as a condition to an `nvarchar` field. But as soon as I apply filter I get the error: > > Incorrect syntax near the keyword SET > > > Looking at the query written by editor I see that the consition is `fldName =`, no sign of my `NULL` check How can I do it? This is th result: ``` SELECT TOP 1000 [Ktyi_TS002_IdTipoDocumento] , [nvc_TS002_TipoDocumento] ,[nvc_TS002_IdFunzioneControllo] ,[bit_TS002_Annullato] FROM [dbo].[TS002_TipoDocumento] WHERE [nvc_TS002_IdFunzioneControllo] = ``` this is some images of the data editor found in google to show what iam talking about to who don't know ssdt: [![enter image description here](https://i.stack.imgur.com/6Ubaq.png)](https://i.stack.imgur.com/6Ubaq.png) [![enter image description here](https://i.stack.imgur.com/9LLWH.png)](https://i.stack.imgur.com/9LLWH.png)
2015/08/27
[ "https://Stackoverflow.com/questions/32253657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2711395/" ]
It seems to be a bug that IS (NOT) NULL expression is not supported in the filter.
You can work around this by creating a new SQL query for that table and type the filter for "`IS NULL`" manually. 1- Right-click the table 2- Click "New Query" 3- Type the SQL statement using `IS NULL` as a filter This should work fine.
32,253,657
I am trying to filter some row of a table with ssdt (left click on table, view data, sort and filter) Here I simply need to add `IS NULL` as a condition to an `nvarchar` field. But as soon as I apply filter I get the error: > > Incorrect syntax near the keyword SET > > > Looking at the query written by editor I see that the consition is `fldName =`, no sign of my `NULL` check How can I do it? This is th result: ``` SELECT TOP 1000 [Ktyi_TS002_IdTipoDocumento] , [nvc_TS002_TipoDocumento] ,[nvc_TS002_IdFunzioneControllo] ,[bit_TS002_Annullato] FROM [dbo].[TS002_TipoDocumento] WHERE [nvc_TS002_IdFunzioneControllo] = ``` this is some images of the data editor found in google to show what iam talking about to who don't know ssdt: [![enter image description here](https://i.stack.imgur.com/6Ubaq.png)](https://i.stack.imgur.com/6Ubaq.png) [![enter image description here](https://i.stack.imgur.com/9LLWH.png)](https://i.stack.imgur.com/9LLWH.png)
2015/08/27
[ "https://Stackoverflow.com/questions/32253657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2711395/" ]
It seems to be a bug that IS (NOT) NULL expression is not supported in the filter.
This is a very ugly hack, but it may work for you. It seems like you need a column name on the left of the = sign to keep the filter parser from changing the query. In my case my column that I was looking for nulls in was an integer, so I needed to get an integer on the left hand side. I also needed a value for the columns that I was looking for nulls in that would not exist for any non-null row. In my case this was 0. ``` Create MyTable ( Id int primary key, ... MyNum int ); ``` To search for rows with nulls in column MyNum, I did this: ``` [Id] - [Id] = IsNull([MyNum],0) ``` The [Id] - [Id] was used to produce 0 and not trigger the parser to re-write the statement as [MyNum] = stuff The right hand side was not re-written by the parser so the NULL values were changed to 0's. I assume for strings you could do something similar, maybe ``` concatenate([OtherStringCol],'XYZZY') = ISNull([MyStrCol],concatenate([OtherStringCol],'XYZZY')) ``` The 'XYZZY' part is used to ensure that you don't get cases where [MyStrCol] = [OtherStringCol]. I am assuming that the string 'XYZZY' doesn't exist in these columns.
32,253,657
I am trying to filter some row of a table with ssdt (left click on table, view data, sort and filter) Here I simply need to add `IS NULL` as a condition to an `nvarchar` field. But as soon as I apply filter I get the error: > > Incorrect syntax near the keyword SET > > > Looking at the query written by editor I see that the consition is `fldName =`, no sign of my `NULL` check How can I do it? This is th result: ``` SELECT TOP 1000 [Ktyi_TS002_IdTipoDocumento] , [nvc_TS002_TipoDocumento] ,[nvc_TS002_IdFunzioneControllo] ,[bit_TS002_Annullato] FROM [dbo].[TS002_TipoDocumento] WHERE [nvc_TS002_IdFunzioneControllo] = ``` this is some images of the data editor found in google to show what iam talking about to who don't know ssdt: [![enter image description here](https://i.stack.imgur.com/6Ubaq.png)](https://i.stack.imgur.com/6Ubaq.png) [![enter image description here](https://i.stack.imgur.com/9LLWH.png)](https://i.stack.imgur.com/9LLWH.png)
2015/08/27
[ "https://Stackoverflow.com/questions/32253657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2711395/" ]
This is a very ugly hack, but it may work for you. It seems like you need a column name on the left of the = sign to keep the filter parser from changing the query. In my case my column that I was looking for nulls in was an integer, so I needed to get an integer on the left hand side. I also needed a value for the columns that I was looking for nulls in that would not exist for any non-null row. In my case this was 0. ``` Create MyTable ( Id int primary key, ... MyNum int ); ``` To search for rows with nulls in column MyNum, I did this: ``` [Id] - [Id] = IsNull([MyNum],0) ``` The [Id] - [Id] was used to produce 0 and not trigger the parser to re-write the statement as [MyNum] = stuff The right hand side was not re-written by the parser so the NULL values were changed to 0's. I assume for strings you could do something similar, maybe ``` concatenate([OtherStringCol],'XYZZY') = ISNull([MyStrCol],concatenate([OtherStringCol],'XYZZY')) ``` The 'XYZZY' part is used to ensure that you don't get cases where [MyStrCol] = [OtherStringCol]. I am assuming that the string 'XYZZY' doesn't exist in these columns.
You can work around this by creating a new SQL query for that table and type the filter for "`IS NULL`" manually. 1- Right-click the table 2- Click "New Query" 3- Type the SQL statement using `IS NULL` as a filter This should work fine.
1,487,369
I have an HTML form, and some users are copy/pasting text from MS Word. When there are single quotes or double quotes, they get translated into funny characters like: '€™ and ’ The database column is collation utf8\_general\_ci. How do I get the appropriate characters to show up? **Edit:** Problem solved. Here's how I fixed it: Ran `mysql_query("SET NAMES 'utf8'");` before adding/retreiving from the database. (thanks to Donal's comment below). And somewhat odd, the php function `urlencode($text)` was applied when displaying, so that had to be removed. I also made sure that the headers for the page and the ajax request/response were all utf8.
2009/09/28
[ "https://Stackoverflow.com/questions/1487369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21456/" ]
This looks like a classic case of unicode (UTF-8 most likely) characters being interpreted as iso-8859-1. There are a couple places along the way where the characters can get corrupted. First, the client's browser has to send the data. It might corrupt the data if it can't convert the characters properly to the page's character encoding. Then the server reads the data and decodes the bytes into characters. If the client and server disagree about the encoding used then the characters will be corrupted. Then the data is stored in the database; again there is potential for corruption. Finally, when the data is written on the page (for display to the browser) the browser may misinterpret the bytes if the page doesn't adequately indicate it's encoding. You need to ensure that you are using UTF-8 throughout. The default for web pages is iso-8859-1, so your web pages should be served with the Content-Type header or the meta tag ``` <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> ``` (make sure you really are serving the text in that encoding). By using UTF-8 along all parts of the process you will avoid problems with all working web browsers and databases.
Check the encoding that the page uses. Encode it using UTF-8 as well, and add a meta tag describing the encoding: ``` <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> ```
1,487,369
I have an HTML form, and some users are copy/pasting text from MS Word. When there are single quotes or double quotes, they get translated into funny characters like: '€™ and ’ The database column is collation utf8\_general\_ci. How do I get the appropriate characters to show up? **Edit:** Problem solved. Here's how I fixed it: Ran `mysql_query("SET NAMES 'utf8'");` before adding/retreiving from the database. (thanks to Donal's comment below). And somewhat odd, the php function `urlencode($text)` was applied when displaying, so that had to be removed. I also made sure that the headers for the page and the ajax request/response were all utf8.
2009/09/28
[ "https://Stackoverflow.com/questions/1487369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21456/" ]
This looks like a classic case of unicode (UTF-8 most likely) characters being interpreted as iso-8859-1. There are a couple places along the way where the characters can get corrupted. First, the client's browser has to send the data. It might corrupt the data if it can't convert the characters properly to the page's character encoding. Then the server reads the data and decodes the bytes into characters. If the client and server disagree about the encoding used then the characters will be corrupted. Then the data is stored in the database; again there is potential for corruption. Finally, when the data is written on the page (for display to the browser) the browser may misinterpret the bytes if the page doesn't adequately indicate it's encoding. You need to ensure that you are using UTF-8 throughout. The default for web pages is iso-8859-1, so your web pages should be served with the Content-Type header or the meta tag ``` <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> ``` (make sure you really are serving the text in that encoding). By using UTF-8 along all parts of the process you will avoid problems with all working web browsers and databases.
We have a PHP function that tries to clean up the mess with smart quotes. It's a bit of a mess, since it's grown a bit organically as cases popped up during prototype development. It may be of some help, though: ``` function convert_smart_quotes($string) { $search = array(chr(0xe2) . chr(0x80) . chr(0x98), chr(0xe2) . chr(0x80) . chr(0x99), chr(0xe2) . chr(0x80) . chr(0x9c), chr(0xe2) . chr(0x80) . chr(0x9d), chr(0xe2) . chr(0x80) . chr(0x93), chr(0xe2) . chr(0x80) . chr(0x94), chr(226) . chr(128) . chr(153), '’','“','â€<9d>','â€"',' '); $replace = array("'","'",'"','"',' - ',' - ',"'","'",'"','"',' - ',' '); return str_replace($search, $replace, $string); } ```
20,598,744
I did it like this – but it is not working: ``` ma f [] = [] ma f (xs) = foldl (\y ys -> ys++(f y)) [] xs foldl :: (a -> b -> a) -> a -> [b] -> a foldr :: (a -> b -> b) -> b -> [a] -> b ``` Why is there a difference in the function that fold takes. I mean, `(a -> b -> a)` and `(a -> b -> b)`? Is it possible to define `map` using `foldl`? I have another question I have an expr. ``` map (:) ``` I want to know what it will do. I tried to test it but i only get error. ``` type is map (:) :: [a] -> [[a] -> [a]] ``` I tried to send in a list of `[1,2,3]`
2013/12/15
[ "https://Stackoverflow.com/questions/20598744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975699/" ]
Not if you want it to work for infinite as well as finite lists. `head $ map id (cycle [1])` must return 1. `foldl`ing over an infinite list diverges (never stops), because `foldl` is recursive. For example, ``` foldl g z [a,b,c] = g (g (g z a) b) c ``` Before `g` gets a chance to ignore its argument, `foldl` must reach the last element of the input list, to construct the first call to `g`. There is no last element in an infinite list. --- As for your *new* question, here's a GHCi transcript that shows that `map (:)` is a function, and `map (:) [1,2,3]` is a list of functions, and GHCi just doesn't know how to `Show` functions: ``` Prelude> map (:) <interactive>:1:0: No instance for (Show ([a] -> [[a] -> [a]])) Prelude> :t map (:) map (:) :: [a] -> [[a] -> [a]] Prelude> map (:) [1,2,3] <interactive>:1:0: No instance for (Show ([a] -> [a])) Prelude> :t map (:) [1,2,3] map (:) [1,2,3] :: (Num a) => [[a] -> [a]] Prelude> map ($ [4]) $ map (:) [1,2,3] [[1,4],[2,4],[3,4]] Prelude> foldr ($) [4] $ map (:) [1,2,3] [1,2,3,4] ```
It becomes more obvious when you swap the type-variable names in one of the functions: ``` foldl :: (b -> a -> b) -> b -> [a] -> b foldr :: (a -> b -> b) -> b -> [a] -> b ``` ...because after all, what we need is the result, i.e. `[a] -> b`. Or, more specially, `[a] -> [b]`, so we might as well substitute that ``` foldl :: ([b] -> a -> [b]) -> [b] -> [a] -> [b] foldr :: (a -> [b] -> [b]) -> [b] -> [a] -> [b] ``` which leaves only one non-list item in each signature, namely the `a`. That's what we can apply `f` to, so, in the case of `foldl` it has to be the **2nd** argument of the lambda: ``` foldl (\ys y -> ys ++ f y) ``` As Xeo remarks, this isn't done yet, because `f y` has type `b`, not `[b]`. I think you can figure out how to fix that yourself...
20,598,744
I did it like this – but it is not working: ``` ma f [] = [] ma f (xs) = foldl (\y ys -> ys++(f y)) [] xs foldl :: (a -> b -> a) -> a -> [b] -> a foldr :: (a -> b -> b) -> b -> [a] -> b ``` Why is there a difference in the function that fold takes. I mean, `(a -> b -> a)` and `(a -> b -> b)`? Is it possible to define `map` using `foldl`? I have another question I have an expr. ``` map (:) ``` I want to know what it will do. I tried to test it but i only get error. ``` type is map (:) :: [a] -> [[a] -> [a]] ``` I tried to send in a list of `[1,2,3]`
2013/12/15
[ "https://Stackoverflow.com/questions/20598744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975699/" ]
Not if you want it to work for infinite as well as finite lists. `head $ map id (cycle [1])` must return 1. `foldl`ing over an infinite list diverges (never stops), because `foldl` is recursive. For example, ``` foldl g z [a,b,c] = g (g (g z a) b) c ``` Before `g` gets a chance to ignore its argument, `foldl` must reach the last element of the input list, to construct the first call to `g`. There is no last element in an infinite list. --- As for your *new* question, here's a GHCi transcript that shows that `map (:)` is a function, and `map (:) [1,2,3]` is a list of functions, and GHCi just doesn't know how to `Show` functions: ``` Prelude> map (:) <interactive>:1:0: No instance for (Show ([a] -> [[a] -> [a]])) Prelude> :t map (:) map (:) :: [a] -> [[a] -> [a]] Prelude> map (:) [1,2,3] <interactive>:1:0: No instance for (Show ([a] -> [a])) Prelude> :t map (:) [1,2,3] map (:) [1,2,3] :: (Num a) => [[a] -> [a]] Prelude> map ($ [4]) $ map (:) [1,2,3] [[1,4],[2,4],[3,4]] Prelude> foldr ($) [4] $ map (:) [1,2,3] [1,2,3,4] ```
``` ma f [] = [] ma f (xs) = foldl (\ys y -> ys++[(f y)]) [] xs ``` Works but why does order of arg to lambda matter. `ma f (xs) = foldl (\y ys -> ys++[(f y)]) [] xs` gives error
60,717,730
I tried to write a code snippet as shown below. Main goal is to read from 03-10-2020.csv to from 03-16-2020.csv and merge them into one dataframe but only last dataframe is included in the dataframe. How can I fix it? ``` week_array = [] path = 'URL_ADDRESS' for i in range(10,17): dataset_date = "03-" + str(i) + "-2020.csv" url = path + dataset_date data_df = pd.read_csv(url, error_bad_lines=False, encoding = "utf-8" , index_col=None, header=0) week_array.append(data_df) week_df = pd.concat(week_array, axis=0, ignore_index=True) ```
2020/03/17
[ "https://Stackoverflow.com/questions/60717730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5719229/" ]
This is what the HtmlHelper class is for. Set the view model in your view file and create a form around it. ``` @model Models.EmployeeModel @using (Html.BeginForm("Edit", "Employees", FormMethod.Post)) { @Html.LabelFor(m => m.fname) @Html.TextBoxFor(m => m.fname) <input type="submit" value="Submit"/> } ``` Invoke the view from your controller with an instance of the model to edit. ``` public IActionResult Edit(int id) { ... employee = service.GetEmployeeById(id); return View(employee); } ```
one thig you could try would be to set values in Razor: ```cs // your controller public class HomeController : Controller { [HttpGet] public ActionResult Index() { return View(new EmployeeModel());// pass the actual viewmodel instance to the view here } } ``` ```cs @model EmployeeModel ....... <form action="/action_page.php"> <label for="fname">First name:</label> <input type="text" id="fname" name="fname" value="@Model.fname"><br><br> <!-- reference @Model fields as usual --> <label for="lname">Last name:</label> <input type="text" id="lname" name="lname" value="@Model.lname"><br><br><!-- reference @Model fields as usual --> <input type="submit" value="Submit"> </form> ``` and a fiddle for you to play with: <https://dotnetfiddle.net/37asAw>
63,529,556
My Javascript build process ends up inserting the keyword `require()` in the file. This is not supported in client side and causes a console error. I have added `browserify` per other SO answers, however, I am in turn getting another error (below). Additional Information: I am using: 1. Gulp 4 2. Node (v14.2.0) Error: ``` [16:03:55] Using gulpfile /mnt/c/code/mutationObserver/gulpfile.js [16:03:55] Starting 'default'... [16:03:55] Starting 'clean'... [16:03:55] Finished 'clean' after 10 ms [16:03:55] Starting 'html'... [16:03:55] Starting 'js'... [16:03:55] Starting 'css'... [16:03:55] Finished 'html' after 46 ms [16:03:55] Finished 'css' after 51 ms [16:03:55] 'js' errored after 54 ms [16:03:55] Error: Can't walk dependency graph: Cannot find module '/mnt/c/code/mutationObserver/src/js/*.js' from '/mnt/c/code/mutationObserver/src/js/_fake.js' required by /mnt/c/code/mutationObserver/src/js/_fake.js at /mnt/c/code/mutationObserver/node_modules/resolve/lib/async.js:136:35 at load (/mnt/c/code/mutationObserver/node_modules/resolve/lib/async.js:155:43) at onex (/mnt/c/code/mutationObserver/node_modules/resolve/lib/async.js:180:17) at /mnt/c/code/mutationObserver/node_modules/resolve/lib/async.js:15:69 at FSReqCallback.oncomplete (fs.js:175:21) [16:03:55] 'default' errored after 69 ms ``` My entire `Gulpfile.js` is as follows: ``` const { series, parallel, watch, src, dest } = require("gulp"); const plumber = require("gulp-plumber"); const del = require("del"); const concat = require("gulp-concat"); const babel = require("gulp-babel"); const sass = require("gulp-sass"); const browserSync = require("browser-sync").create(); const browserify = require('browserify') const source = require('vinyl-source-stream') function html() { return src("./src/*.html").pipe(dest("./dist")); } function css() { return src("./src/css/style.scss") .pipe(plumber()) .pipe(sass().on("error", sass.logError)) .pipe(dest("./dist/css")); } function js() { return browserify("./src/js/*.js") .bundle() .pipe(source("main.js")) .pipe(plumber()) .pipe( babel({ presets: ["@babel/env"], plugins: ["@babel/transform-runtime"], }) ) .pipe(dest("./dist/js")); } function clean() { return del(["./dist"]); } function watchFor() { browserSync.init({ server: { baseDir: "./dist/", }, }); // first rerun the function that distributed the css files, then reload the browser watch("./src/css/**/*.scss").on("change", css); watch("./dist/css/*.css").on("change", browserSync.reload); // first rerun the function that distributed the javascript files, then reload the browser watch("./src/js/*.js").on("change", js); watch("./dist/js/*.js").on("change", browserSync.reload); // first rerun the function that writes to the dist folder, then reload the browser watch("./src/*.html").on("change", html); watch("./dist/*.html").on("change", browserSync.reload); } exports.clean = clean; exports.css = css; exports.js = js; exports.html = html; exports.watch = watch; exports.default = series(clean, parallel(html, js, css), watchFor); ```
2020/08/21
[ "https://Stackoverflow.com/questions/63529556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12369920/" ]
I had the same error. This error means that it cannot find the required js file. Make sure that the file is in the correct folder, as specified in "required", and if it's in the same folder, you might need to add ./ . browserify main.js -o bundle.js ``` Error: Can't walk dependency graph: Cannot find module 'srt' from 'C:\code\html1\main.js' ``` In my main.js error, I changed: ``` var srt = require('srt'); ``` to: ``` var srt = require('./srt'); ``` And then it worked.
My case was slightly different. I had just moved from Windows to Ubuntu (via WSL). Double checked the package was installed, removed and re-installed locally and globally, still cannot find module. This previously worked when on windows: `window.Example = require('Example');` Turns out **Linux case sensitivity** meant it needed to be: `window.Example = require('example');`
15,880,730
I need to extract the Maven GAV (groupId, artifactId, version) from a large number of `pom.xml` files. Not all of the POMs have a parent POM declaration, so the inheritance between parent GAV and project GAV needs to be taken into account. I'd only like to use tools that can be easily scripted in a linux shell, e.g. bash.
2013/04/08
[ "https://Stackoverflow.com/questions/15880730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1523648/" ]
``` grep -v '\[' <( mvn help:evaluate -Dexpression="project.groupId" 2>/dev/null && mvn help:evaluate -Dexpression="project.artifactId" 2>/dev/null && mvn help:evaluate -Dexpression="project.version" 2>/dev/null ) ```
The best solution I could find is using an XSL transformation. Create a file `extract-gav.xsl` with the following content: ```xml <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:pom="http://maven.apache.org/POM/4.0.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes" omit-xml-declaration="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="/pom:project"> <!-- this XML element just serves as a bracket and may be omitted --> <xsl:element name="artifact"> <xsl:text>&#10;</xsl:text> <!-- process coordinates declared at project and project/parent --> <xsl:apply-templates select="pom:groupId|pom:parent/pom:groupId" mode="copy-coordinate"/> <xsl:apply-templates select="pom:artifactId|pom:parent/pom:artifactId" mode="copy-coordinate"/> <xsl:apply-templates select="pom:version|pom:parent/pom:version" mode="copy-coordinate"/> </xsl:element> </xsl:template> <xsl:template match="*" mode="copy-coordinate"> <!-- omit parent coordinate if same coordinate is explicitly specified on project level --> <xsl:if test="not(../../*[name(.)=name(current())])"> <!-- write coordinate as XML element without namespace declarations --> <xsl:element name="{local-name()}"> <xsl:value-of select="."/> </xsl:element> <xsl:text>&#10;</xsl:text> </xsl:if> </xsl:template> </xsl:stylesheet> ``` This transformation can then be invoked in a shell (assuming that you have the libxslt installed) with th command `xsltproc extract-gav.xsl pom.xml` This produces the output in the following format: ```xml <artifact> <groupId>org.example.group</groupId> <artifactId>example-artifact</artifactId> <version>1.2.0</version> </artifact> ``` If you need a different format, the XSL transformation should be easy enough to adapt so that it suits your needs. E.g. the following transformation writes the GAV as tab-separated plain text: ```xml <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:pom="http://maven.apache.org/POM/4.0.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="/pom:project"> <!-- process coordinates declared at project and project/parent --> <xsl:apply-templates select="pom:groupId|pom:parent/pom:groupId" mode="copy-coordinate"/> <xsl:apply-templates select="pom:artifactId|pom:parent/pom:artifactId" mode="copy-coordinate"/> <xsl:apply-templates select="pom:version|pom:parent/pom:version" mode="copy-coordinate"/> <xsl:text>&#10;</xsl:text> </xsl:template> <xsl:template match="*" mode="copy-coordinate"> <xsl:if test="not(../../*[name(.)=name(current())])"> <xsl:value-of select="."/> <xsl:text>&#9;</xsl:text> </xsl:if> </xsl:template> </xsl:stylesheet> ```
15,880,730
I need to extract the Maven GAV (groupId, artifactId, version) from a large number of `pom.xml` files. Not all of the POMs have a parent POM declaration, so the inheritance between parent GAV and project GAV needs to be taken into account. I'd only like to use tools that can be easily scripted in a linux shell, e.g. bash.
2013/04/08
[ "https://Stackoverflow.com/questions/15880730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1523648/" ]
The best solution I could find is using an XSL transformation. Create a file `extract-gav.xsl` with the following content: ```xml <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:pom="http://maven.apache.org/POM/4.0.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes" omit-xml-declaration="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="/pom:project"> <!-- this XML element just serves as a bracket and may be omitted --> <xsl:element name="artifact"> <xsl:text>&#10;</xsl:text> <!-- process coordinates declared at project and project/parent --> <xsl:apply-templates select="pom:groupId|pom:parent/pom:groupId" mode="copy-coordinate"/> <xsl:apply-templates select="pom:artifactId|pom:parent/pom:artifactId" mode="copy-coordinate"/> <xsl:apply-templates select="pom:version|pom:parent/pom:version" mode="copy-coordinate"/> </xsl:element> </xsl:template> <xsl:template match="*" mode="copy-coordinate"> <!-- omit parent coordinate if same coordinate is explicitly specified on project level --> <xsl:if test="not(../../*[name(.)=name(current())])"> <!-- write coordinate as XML element without namespace declarations --> <xsl:element name="{local-name()}"> <xsl:value-of select="."/> </xsl:element> <xsl:text>&#10;</xsl:text> </xsl:if> </xsl:template> </xsl:stylesheet> ``` This transformation can then be invoked in a shell (assuming that you have the libxslt installed) with th command `xsltproc extract-gav.xsl pom.xml` This produces the output in the following format: ```xml <artifact> <groupId>org.example.group</groupId> <artifactId>example-artifact</artifactId> <version>1.2.0</version> </artifact> ``` If you need a different format, the XSL transformation should be easy enough to adapt so that it suits your needs. E.g. the following transformation writes the GAV as tab-separated plain text: ```xml <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:pom="http://maven.apache.org/POM/4.0.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="/pom:project"> <!-- process coordinates declared at project and project/parent --> <xsl:apply-templates select="pom:groupId|pom:parent/pom:groupId" mode="copy-coordinate"/> <xsl:apply-templates select="pom:artifactId|pom:parent/pom:artifactId" mode="copy-coordinate"/> <xsl:apply-templates select="pom:version|pom:parent/pom:version" mode="copy-coordinate"/> <xsl:text>&#10;</xsl:text> </xsl:template> <xsl:template match="*" mode="copy-coordinate"> <xsl:if test="not(../../*[name(.)=name(current())])"> <xsl:value-of select="."/> <xsl:text>&#9;</xsl:text> </xsl:if> </xsl:template> </xsl:stylesheet> ```
I use a groovy script called **pom** that I placed on PATH. It looks like this: ``` #!/usr/bin/env groovy def cli = new CliBuilder(usage:'pom') cli.h('print usage') cli.n('do not auto-print output') cli.p(args:1, argName:'pom', 'the POM file to use') def options = cli.parse(args) def arguments = options.arguments() if (options.h || arguments.size() == 0 ) { println cli.usage() } else { def fileName = options.p ? options.p : "pom.xml" def script = arguments[0] def output = Eval.x(new XmlSlurper().parse(new File(fileName)), "x.${script}") if (!options.n) println output } ``` Now you can extract values like this: ``` pom version pom groupId pom 'properties."project.build.sourceEncoding"' pom -n 'modules.module.each { println it }' pom -n 'dependencyManagement.dependencies.dependency.each { \ println "${it.groupId}:${it.artifactId}:${it.version}" \ }' ```
15,880,730
I need to extract the Maven GAV (groupId, artifactId, version) from a large number of `pom.xml` files. Not all of the POMs have a parent POM declaration, so the inheritance between parent GAV and project GAV needs to be taken into account. I'd only like to use tools that can be easily scripted in a linux shell, e.g. bash.
2013/04/08
[ "https://Stackoverflow.com/questions/15880730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1523648/" ]
``` grep -v '\[' <( mvn help:evaluate -Dexpression="project.groupId" 2>/dev/null && mvn help:evaluate -Dexpression="project.artifactId" 2>/dev/null && mvn help:evaluate -Dexpression="project.version" 2>/dev/null ) ```
I use a groovy script called **pom** that I placed on PATH. It looks like this: ``` #!/usr/bin/env groovy def cli = new CliBuilder(usage:'pom') cli.h('print usage') cli.n('do not auto-print output') cli.p(args:1, argName:'pom', 'the POM file to use') def options = cli.parse(args) def arguments = options.arguments() if (options.h || arguments.size() == 0 ) { println cli.usage() } else { def fileName = options.p ? options.p : "pom.xml" def script = arguments[0] def output = Eval.x(new XmlSlurper().parse(new File(fileName)), "x.${script}") if (!options.n) println output } ``` Now you can extract values like this: ``` pom version pom groupId pom 'properties."project.build.sourceEncoding"' pom -n 'modules.module.each { println it }' pom -n 'dependencyManagement.dependencies.dependency.each { \ println "${it.groupId}:${it.artifactId}:${it.version}" \ }' ```
70,050,381
So I creating a movie-db app and I want to toggle between different categories like `Top Rated`,`Popular` etc.I am trying to do this by setting the state to be the text value of whatever clicked which will be used later on to form the complete url to be fetched. This is my code: `App.js` ``` import Movie from "./components/Movie"; import requests from "./components/ApiRequest"; import Navbar from "./components/Navbar"; function App() { return ( <div className="App"> <Navbar /> <div className="movie-container"> <Movie fetchUrl={requests.fetchTrending} /> </div> </div> ); } export default App; ``` `Navbar.js` ``` import React, { useState } from 'react' import SearchBar from './SearchBar' import { FiFilter } from 'react-icons/fi' import requests from "../components/ApiRequest"; const Navbar = () => { const [category, setCategory] = useState('Trending') return ( <div className="navbar-container"> <button className="navbar-btn"><FiFilter />Filter</button> <div className="categories"> <button onClick={() => setCategory("Trending")}>Trending</button> <button onClick={() => setCategory("Popular")}>Popular</button> <button onClick={() => setCategory("TopRated")}>Top Rated</button> <button onClick={() => setCategory("Upcoming")}>Upcoming</button> </div> <SearchBar /> </div> ) } ``` So I want to get the value of `category` from `Navbar.js` outside the function and use it here `<Movie fetchUrl={requests.fetch{category} />` so that I can fetch that url from requests
2021/11/20
[ "https://Stackoverflow.com/questions/70050381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13412737/" ]
You should lift state up to a common ancestor, i.e. `App` in this case, where it can be passed down as props to children components. Example: ``` function App() { const [category, setCategory] = useState('Trending'); return ( <div className="App"> <Navbar setCategory={setCategory}/> <div className="movie-container"> <Movie fetchUrl={requests.fetchTrending(category)} /> </div> </div> ); } ``` ... ``` const Navbar = ({ setCategory }) => { return ( <div className="navbar-container"> <button className="navbar-btn"><FiFilter />Filter</button> <div className="categories"> <button onClick={() => setCategory("Trending")}>Trending</button> <button onClick={() => setCategory("Popular")}>Popular</button> <button onClick={() => setCategory("TopRated")}>Top Rated</button> <button onClick={() => setCategory("Upcoming")}>Upcoming</button> </div> <SearchBar /> </div> ) } ```
You need to lift up your state. It means that your useState 'category' hook have to be in parent component which can pass this data as prop to child. In your case parent component for Movie component is App component so App component have to contain ``` const [category, setCategory] = useState('Trending') ``` Now you can pass 'category' prop to Movie component and setCategory to Navbar component
61,967,282
Write a function called push which accepts two parameters, an array and any value. The function should add the value to the end of the array and then return the new length of the array. Do not use the built in `Array.push() function!` Examples: ``` var arr = [1, 2, 3]; push(arr, 10); // 4 arr; // [1, 2, 3, 10] ``` My question is `How to return a new array with the new length`.
2020/05/23
[ "https://Stackoverflow.com/questions/61967282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13586804/" ]
To install `Firebase` in your project, prerequisites are : 1. Install the following: > > Xcode 10.3 or later CocoaPods 1.4.0 or later > > > 2. Make sure that your project meets these requirements: > > Your project must target iOS 8 or later. > > > [Reference](https://firebase.google.com/docs/ios/setup) Below `pod file` can be used to install the dependencies, ``` use_frameworks! platform :ios, '8.0' install! 'cocoapods' target 'Test' do use_frameworks! pod 'Firebase/Analytics' pod 'Firebase/Messaging' end ```
step 1: To add pod file pod 'Firebase', '>= 2.5.1' pod ‘Firebase/Core’ pod ‘Firebase/Database’ pod ‘Firebase/Auth’ step 2: pod install
18,689,447
[Here's what I've got](http://jsfiddle.net/mnbayazit/KDN8s/): **HTML** ```html <div class="combobox"> <input type="text" value="" name="brand" class="text" id="brand"> <span class="dropdown_btn"></span> </div> ``` **CSS** ```css .combobox { margin: 0; padding: 0; vertical-align: middle; } .combobox input { height: 20px; line-height: 20px; margin: 0; padding: 0; } .combobox .dropdown_btn { width: 18px; height: 20px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; } ``` But it comes out like this: ![](https://i.imgur.com/5YIpr0M.png) I don't know where the gap is coming from; why isn't the text input snug against its container div like the blue button is?
2013/09/08
[ "https://Stackoverflow.com/questions/18689447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
Try this to add `vertical-align: middle;` to `.combobox .dropdown_btn` and remove it from the `combobox` class: ``` .combobox .dropdown_btn { width: 18px; height: 20px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; vertical-align: middle; } ```
``` .combobox .dropdown_btn { width: 18px; height: 20px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; vertical-align: middle; } ``` <http://jsfiddle.net/KDN8s/5/>
18,689,447
[Here's what I've got](http://jsfiddle.net/mnbayazit/KDN8s/): **HTML** ```html <div class="combobox"> <input type="text" value="" name="brand" class="text" id="brand"> <span class="dropdown_btn"></span> </div> ``` **CSS** ```css .combobox { margin: 0; padding: 0; vertical-align: middle; } .combobox input { height: 20px; line-height: 20px; margin: 0; padding: 0; } .combobox .dropdown_btn { width: 18px; height: 20px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; } ``` But it comes out like this: ![](https://i.imgur.com/5YIpr0M.png) I don't know where the gap is coming from; why isn't the text input snug against its container div like the blue button is?
2013/09/08
[ "https://Stackoverflow.com/questions/18689447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
Try setting the `vertical-align:top` to `input` <http://jsfiddle.net/KDN8s/4/> ```css .combobox { margin: 0; padding: 0; } .combobox input { margin: 0; padding: 0; height: 20px; vertical-align: top; } .combobox .dropdown_btn { width: 20px; height: 24px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; } ``` ```html <div class="combobox"> <input type="text" value="" name="brand" class="text" id="brand"> <span class="dropdown_btn"></span> </div> ```
Try this to add `vertical-align: middle;` to `.combobox .dropdown_btn` and remove it from the `combobox` class: ``` .combobox .dropdown_btn { width: 18px; height: 20px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; vertical-align: middle; } ```
18,689,447
[Here's what I've got](http://jsfiddle.net/mnbayazit/KDN8s/): **HTML** ```html <div class="combobox"> <input type="text" value="" name="brand" class="text" id="brand"> <span class="dropdown_btn"></span> </div> ``` **CSS** ```css .combobox { margin: 0; padding: 0; vertical-align: middle; } .combobox input { height: 20px; line-height: 20px; margin: 0; padding: 0; } .combobox .dropdown_btn { width: 18px; height: 20px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; } ``` But it comes out like this: ![](https://i.imgur.com/5YIpr0M.png) I don't know where the gap is coming from; why isn't the text input snug against its container div like the blue button is?
2013/09/08
[ "https://Stackoverflow.com/questions/18689447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
You need to apply `vertical-align: middle` to your inline elements: ``` .combobox { margin: 0; padding: 0; } .combobox input { height: 20px; line-height: 20px; margin: 0; padding: 0; vertical-align: middle; } .combobox .dropdown_btn { width: 18px; height: 20px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; vertical-align: middle; } ``` See: [JSFiddle](http://jsfiddle.net/audetwebdesign/8GpxP/) The `vertical-align` property is not inherited, so you need to specify it to any inline elements that you want to adjust.
``` .combobox .dropdown_btn { width: 18px; height: 20px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; vertical-align: middle; } ``` <http://jsfiddle.net/KDN8s/5/>
18,689,447
[Here's what I've got](http://jsfiddle.net/mnbayazit/KDN8s/): **HTML** ```html <div class="combobox"> <input type="text" value="" name="brand" class="text" id="brand"> <span class="dropdown_btn"></span> </div> ``` **CSS** ```css .combobox { margin: 0; padding: 0; vertical-align: middle; } .combobox input { height: 20px; line-height: 20px; margin: 0; padding: 0; } .combobox .dropdown_btn { width: 18px; height: 20px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; } ``` But it comes out like this: ![](https://i.imgur.com/5YIpr0M.png) I don't know where the gap is coming from; why isn't the text input snug against its container div like the blue button is?
2013/09/08
[ "https://Stackoverflow.com/questions/18689447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
Try setting the `vertical-align:top` to `input` <http://jsfiddle.net/KDN8s/4/> ```css .combobox { margin: 0; padding: 0; } .combobox input { margin: 0; padding: 0; height: 20px; vertical-align: top; } .combobox .dropdown_btn { width: 20px; height: 24px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; } ``` ```html <div class="combobox"> <input type="text" value="" name="brand" class="text" id="brand"> <span class="dropdown_btn"></span> </div> ```
You need to apply `vertical-align: middle` to your inline elements: ``` .combobox { margin: 0; padding: 0; } .combobox input { height: 20px; line-height: 20px; margin: 0; padding: 0; vertical-align: middle; } .combobox .dropdown_btn { width: 18px; height: 20px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; vertical-align: middle; } ``` See: [JSFiddle](http://jsfiddle.net/audetwebdesign/8GpxP/) The `vertical-align` property is not inherited, so you need to specify it to any inline elements that you want to adjust.
18,689,447
[Here's what I've got](http://jsfiddle.net/mnbayazit/KDN8s/): **HTML** ```html <div class="combobox"> <input type="text" value="" name="brand" class="text" id="brand"> <span class="dropdown_btn"></span> </div> ``` **CSS** ```css .combobox { margin: 0; padding: 0; vertical-align: middle; } .combobox input { height: 20px; line-height: 20px; margin: 0; padding: 0; } .combobox .dropdown_btn { width: 18px; height: 20px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; } ``` But it comes out like this: ![](https://i.imgur.com/5YIpr0M.png) I don't know where the gap is coming from; why isn't the text input snug against its container div like the blue button is?
2013/09/08
[ "https://Stackoverflow.com/questions/18689447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
Try setting the `vertical-align:top` to `input` <http://jsfiddle.net/KDN8s/4/> ```css .combobox { margin: 0; padding: 0; } .combobox input { margin: 0; padding: 0; height: 20px; vertical-align: top; } .combobox .dropdown_btn { width: 20px; height: 24px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; } ``` ```html <div class="combobox"> <input type="text" value="" name="brand" class="text" id="brand"> <span class="dropdown_btn"></span> </div> ```
``` .combobox .dropdown_btn { width: 18px; height: 20px; margin-left: -20px; display: inline-block; cursor: pointer; background-color: blue; vertical-align: middle; } ``` <http://jsfiddle.net/KDN8s/5/>
46,653,569
EDIT: originally I checked only desktop browsers - but with mobile browsers, the picture is even more complicated. I came across a strange issue with some browsers and its text rendering capabilities and I am not sure if I can do anything to avoid this. It seems WebKit and (less consistent) Firefox on Android are creating slightly larger text using the 2D Canvas library. I would like to ignore the visual appearance for now, but instead focus on the text measurements, as those can be easily compared. I have used the two common methods to calculate the text width: * Canvas 2D API and measure text * DOM method as outlined in this question: [Calculate text width with JavaScript](https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393) however, both yield to more or less the same result (across all browsers). ``` function getTextWidth(text, font) { // if given, use cached canvas for better performance // else, create new canvas var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas")); var context = canvas.getContext("2d"); context.font = font; var metrics = context.measureText(text); return metrics.width; }; function getTextWidthDOM(text, font) { var f = font || '12px arial', o = $('<span>' + text + '</span>') .css({'font': f, 'float': 'left', 'white-space': 'nowrap'}) .css({'visibility': 'hidden'}) .appendTo($('body')), w = o.width(); return w; } ``` I modified the fiddle a little using Google fonts which allows to perform text measurements for a set of sample fonts (please wait for the webfonts to be loaded first before clicking the measure button): <http://jsfiddle.net/aj7v5e4L/15/> (updated to force font-weight and style) Running this on various browsers shows the problem I am having (using the string 'S'): [![Measurements for the string 'S'](https://i.stack.imgur.com/CZ9hj.png)](https://i.stack.imgur.com/CZ9hj.png) The differences across all desktop browsers are minor - only Safari stands out like that - it is in the range of around 1% and 4% what I've seen, depending on the font. So it is not big - but throws off my calculations. UPDATE: Tested a few mobile browsers too - and on iOS all are on the same level as Safari (using WebKit under the hood, so no suprise) - and Firefox on Android is very on and off. I've read that subpixel accuracy isn't really supported across all browsers (older IE's for example) - but even rounding doesn't help - as I then can end up having different width. Using no webfont but just the standard font the context comes with returns the exact same measurements between Chrome and Safari - so I think it is related to webfonts only. I am a bit puzzled of what I might be able to do now - as I think I just do something wrong as I haven't found anything on the net around this - but the fiddle is as simple as it can get. I have spent the entire day on this really - so you guys are my only hope now. I have a few ugly workarounds in my head (e.g. rendering the text on affected browsers 4% smaller) - which I would really like to avoid.
2017/10/09
[ "https://Stackoverflow.com/questions/46653569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1764621/" ]
It seems that Safari (and a few others) does support getting at sub-pixel level, but not drawing... When you set your font-size to `9.5pt`, this value gets converted to 12.6666...**px**. Even though Safari does return an high precision value for this: ```js console.log(getComputedStyle(document.body)['font-size']); // on Safari returns 12.666666984558105px oO ``` ```css body{font-size:9.5pt} ``` it is unable to correctly draw at non-integer font-sizes, and not only on a canvas: ```js console.log(getRangeWidth("S", '12.3px serif')); // safari: 6.673828125 | FF 6.8333282470703125 console.log(getRangeWidth("S", '12.4px serif')); // safari: 6.673828125 | FF 6.883331298828125 console.log(getRangeWidth("S", '12.5px serif')); // safari 7.22998046875 | FF 6.95001220703125 console.log(getRangeWidth("S", '12.6px serif')); // safari 7.22998046875 | FF 7 // High precision DOM based measurement function getRangeWidth(text, font) { var f = font || '12px arial', o = $('<span>' + text + '</span>') .css({'font': f, 'white-space': 'nowrap'}) .appendTo($('body')), r = document.createRange(); r.selectNode(o[0]); var w = r.getBoundingClientRect().width; o.remove(); return w; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ``` So in order to avoid these quirks, ***Try to always use `px` unit with integer values.***
I found below solution from MDN more helpful for scenarios where fonts are slanted/italic which was for me the case with some google fonts copying the snippet from here - <https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics#Measuring_text_width> ``` const computetextWidth = (text, font) => { const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); context.font = font; const { actualBoundingBoxLeft, actualBoundingBoxRight } = context.measureText(text); return Math.ceil(Math.abs(actualBoundingBoxLeft) + Math.abs(actualBoundingBoxRight)); } ```
346,255
$n \mathbb{Z}$ with usual addition and multiplication. Here is what I have: Let $R = \langle n \mathbb{Z}, +, \cdot\rangle$. $R$ is closed under $+$ and under $\cdot$. $R$ is a ring since $\langle n \mathbb{Z}, +\rangle$ is an abelian group, multiplication is associative, and left/right distributive laws hold. Now, $R$ is a commutative ring since $nx \cdot ny = ny \cdot nx$. I also said $R$ is unitary by setting $n = 1, y = 1$. I also said it's a field since $n$ is an arbitrary value (the question doesn't specify that this be an integer). My professor's solution says that $R$ is unitary *unless* $n=1$. It also says that $R$ is not a field. What am I doing wrong? Thanks so much for helping.
2013/03/30
[ "https://math.stackexchange.com/questions/346255", "https://math.stackexchange.com", "https://math.stackexchange.com/users/66368/" ]
If $n=k$, then $P\_1=P\_2=\mathbb{R}^n$ and you can take the zero subspace. So, we can assume there is a non-zero vector $e\in \mathbb{R}^n-P\_1$. Case 1: $e\notin P\_2$. Set $e\_1:=e$. Case 2: $e\in P\_2$. Find $x\in P\_1$ such that $x\notin P\_2$, then $e+x\notin P\_1$ and $e+x\notin P\_2$. Set $e\_1:=e+x$. It is clear that $P\_1\oplus \langle e\_1\rangle$ and $P\_2\oplus \langle e\_1 \rangle$ are two $k+1$-dimensional subspaces of $\mathbb{R}^n$. If $P\_1\oplus \langle e\_1\rangle\neq \mathbb{R}^n$, you can repeat this process for these two subspaces to find $e\_2$. By induction, you find $e\_1,\cdots, e\_{n-k}$ such that they are independent and non of them belong to $P\_1$ or $P\_2$. The subspace generated by $e\_1,\cdots, e\_{n-k}$ is your answer. Edit: In order to address the issue raised by @GeorgesElencwajg , we have to note that not only $e\_1,\cdots,e\_{n-k}$ are linearly independent, but also no non-trivial linear combinations of $e\_1,\cdots,e\_{n-k}$ belongs to $P\_i$ for $i=1,2$. And this claim can be easily verified regarding our construction.
For $j=1,2,\ldots,m$, let $B\_j$ be a basis of $P\_j$. It suffices to find a set of vectors $S=\{v\_1,v\_2,\ldots,v\_{n-k}\}$ such that $S\cup B\_j$ is a linearly independent set of vectors for each $j$. We will begin with $S=\phi$ and put vectors into $S$ one by one. Suppose $S$ already contains $i<n-k$ vectors. Now consider a vector $v\_{i+1}=v\_{i+1}(x)$ of the form $(1,x,x^2,\ldots,x^{n-1})^T$. For each $j$, there are at most $n-1$ different values of $x$ such that $v\_{i+1}(x)\in\operatorname{span}\left(\{v\_1,v\_2,\ldots,v\_i\}\cup B\_j\right)$, otherwise there would exist a non-invertible Vandermonde matrix that corresponds to distinct interpolation nodes. Therefore, there exist some $x$ such that $v\_{i+1}(x)\notin\operatorname{span}\left(\{v\_1,v\_2,\ldots,v\_i\}\cup B\_j\right)$ for all $j$. Put this $v\_{i+1}$ into $S$, $S\cup B\_j$ is a linearly independent set. Continue in this manner until $S$ contains $n-k$ vectors. The resulting $\operatorname{span}(S)$ is the subspace we desire.
52,502,401
I'm trying to figure out how to split up spring integration flows into multiple sub flows and compose them together. Ultimately, I'm trying to lay out a pattern in which I can create modules of subflows that can be pieced together for common integration recipes. This test case represents a minimal example of trying (but failing) to wire together subflows using the DSL IntegrationFlow API: ``` @RunWith(SpringRunner.class) @SpringBootTest(classes = { ComposedIntegrationFlowTest.class }) @SpringIntegrationTest @EnableIntegration public class ComposedIntegrationFlowTest { @Test public void test() { MessageChannel beginningChannel = MessageChannels.direct("beginning").get(); IntegrationFlow middleFlow = f -> f .transform("From middleFlow: "::concat) .transform(String.class, String::toUpperCase); IntegrationFlow endFlow = f -> f .handle((p, h) -> "From endFlow: " + p); StandardIntegrationFlow composedFlow = IntegrationFlows .from(beginningChannel) .gateway(middleFlow) .gateway(endFlow) .get(); composedFlow.start(); beginningChannel.send(MessageBuilder.withPayload("hello!").build()); } } ``` Trying the above, I get: ``` org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'beginning'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers, failedMessage=GenericMessage [payload=hello!, headers={id=2b1de253-a822-42ba-cd85-009b83a644eb, timestamp=1537890950879}], failedMessage=GenericMessage [payload=hello!, headers={id=2b1de253-a822-42ba-cd85-009b83a644eb, timestamp=1537890950879}] ``` How do I piece together these subflows? Is there a better API for attempting to do this kind of composition? Is this integration test structured correctly?
2018/09/25
[ "https://Stackoverflow.com/questions/52502401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3377183/" ]
Try this: ``` SELECT * FROM (SELECT SomeColumn, ..., ROW_NUMBER() OVER (ORDER BY SomeColumn) AS RowNumber FROM table) Aux WHERE RowNumber >= @start AND RowNumber < (@start + @length) ``` Notes: You need mandatory order by a column and also you have to make a subquery to get access to `RowNumber` in the `WHERE` clause
You can try this approach: ``` SELECT ID, ItemID, ItemName, UnitCost, UnitPrice FROM ( SELECT ID, ItemID, ItemName, UnitCost, UnitPrice, ROW_NUMBER() OVER (ORDER BY UnitCost) AS Seq FROM dbo.Inventory )t WHERE Seq BETWEEN 100 AND 200 ``` you will basically use row\_number to fetch they information that you need.
1,177,066
I really want to dump my Windows 7 on my other computer, because Ubuntu is much better. But on that computer, I get no sound on Ubuntu but when it's on Windows, it works fine. I have checked settings, it lists my onboard audio and that is what is selected, and turned on (not muted). I installed Ubuntu on this computer too without any problems. On this computer (that has sound), I remember that I installed Ubuntu 14 and then updated to 18.04. I'd hate to have to do a complete reinstall on that other computer, so is there anyone who knows enough if that was the difference? This working one is a newer motherboard/cpu. [![enter image description here](https://i.stack.imgur.com/4rJeX.jpg)](https://i.stack.imgur.com/4rJeX.jpg)
2019/09/27
[ "https://askubuntu.com/questions/1177066", "https://askubuntu.com", "https://askubuntu.com/users/661173/" ]
`sudo apt install telegram-desktop`
need use: ``` snap changes ``` and find status Doing and kill this ID ``` snap abort <ID> ``` PROFIT!
1,177,066
I really want to dump my Windows 7 on my other computer, because Ubuntu is much better. But on that computer, I get no sound on Ubuntu but when it's on Windows, it works fine. I have checked settings, it lists my onboard audio and that is what is selected, and turned on (not muted). I installed Ubuntu on this computer too without any problems. On this computer (that has sound), I remember that I installed Ubuntu 14 and then updated to 18.04. I'd hate to have to do a complete reinstall on that other computer, so is there anyone who knows enough if that was the difference? This working one is a newer motherboard/cpu. [![enter image description here](https://i.stack.imgur.com/4rJeX.jpg)](https://i.stack.imgur.com/4rJeX.jpg)
2019/09/27
[ "https://askubuntu.com/questions/1177066", "https://askubuntu.com", "https://askubuntu.com/users/661173/" ]
`sudo apt install telegram-desktop`
Just wait a little bit While the software is being downloaded and installed, hitting the install button again and again, pops up that message.
1,177,066
I really want to dump my Windows 7 on my other computer, because Ubuntu is much better. But on that computer, I get no sound on Ubuntu but when it's on Windows, it works fine. I have checked settings, it lists my onboard audio and that is what is selected, and turned on (not muted). I installed Ubuntu on this computer too without any problems. On this computer (that has sound), I remember that I installed Ubuntu 14 and then updated to 18.04. I'd hate to have to do a complete reinstall on that other computer, so is there anyone who knows enough if that was the difference? This working one is a newer motherboard/cpu. [![enter image description here](https://i.stack.imgur.com/4rJeX.jpg)](https://i.stack.imgur.com/4rJeX.jpg)
2019/09/27
[ "https://askubuntu.com/questions/1177066", "https://askubuntu.com", "https://askubuntu.com/users/661173/" ]
need use: ``` snap changes ``` and find status Doing and kill this ID ``` snap abort <ID> ``` PROFIT!
Just wait a little bit While the software is being downloaded and installed, hitting the install button again and again, pops up that message.
8,946
In general, Wisdom can be (and is, and was) identified as Jesus. However, there is this verse: > > [**Proverbs 8:22 (NLT)**](http://www.biblegateway.com/passage/?search=proverbs%208:22&version=NLT) > > 22 "The Lord formed me from the beginning, > >          before he created anything else." > > > Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time? How is the identity of Wisdom established as being that of the Son and how is Proverbs 8:22 handled? If it makes a difference, I grew up Wesleyan, so I'd prefer Protestant doctrines although Catholic or Orthodox doctrines would be interesting too.
2012/08/07
[ "https://christianity.stackexchange.com/questions/8946", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
Note: Most on-line commentaries seem ascribe this verse to mean the Son of God and the Arian heresy tried to use it as a means for arguing that the Son was created and therefore not eternal. See these commentaries [here](http://bible.cc/proverbs/8-22.htm). --- Anyway, when thinking of the Eternal Son as the wisdom of God we run into the idea that the Son was eternally begotten of the Father. That is, the Son from eternity is the express image and word of the father, proceeding from him. Absolutely considered we can’t say that He was ‘formed’ so it seems when the Bible refers to the Son in this way, it is also looking at this with the eternal counsels of God’s will, in the future plan of incarnating the Son and saving the world, before he ever created it. In this sense the Son is both the ‘power and wisdom of God’, before the creation of the world. > > but to those whom God has called, both Jews and Greeks, Christ the power of God and the wisdom of God. (1 Corinthians 1:24) > > > So when we regard that God was planning from eternity to create and redeem the creation by the Son, the Son is said to be God’s wisdom. It is from eternity, in the thought of this undertaking by the Son, that the verse you mention seems to comprehend. We can see that this wisdom, or counsels of God’s will through His Son, were from eternity: > > 3 Praise be to the God and Father of our Lord Jesus Christ, who has blessed us in the heavenly realms with every spiritual blessing in Christ. 4 For he chose us in him before the creation of the world to be holy and blameless in his sight. In love 5 he predestined us for adoption to sonship through Jesus Christ, in accordance with his pleasure and will— 6 to the praise of his glorious grace, which he has freely given us in the One he loves. (Ephesians 1:3-6) > > >
This article by CRI is useful: <https://www.equip.org/article/who-is-wisdom-in-proverbs-8/> They make the case that the literary form of encomium is being used. An encomium is the praise of a character quality, offered so as to persuade others to imitate it. It is poetic and it is fiction. It uses personification. Another example of an encomium in the Bible is 1 Corinthians 13, about love. They list some defining elements of an encomium: > > The writer of an encomium conducts the praise by using a standard set > of literary motifs (elements): (1) introduction to the subject, (2) > the distinguished and ancient ancestry of the subject, (3) a list of > the praiseworthy acts and qualities of the subject, (4) the > indispensable and/or superior nature of the subject, and (5) a > conclusion urging the reader to emulate the subject. > > > Thus this passage does not refer to Jesus at all, so cannot be used to argue (as the article says the Jehovah's Witnesses do) that Christ is a created being.
8,946
In general, Wisdom can be (and is, and was) identified as Jesus. However, there is this verse: > > [**Proverbs 8:22 (NLT)**](http://www.biblegateway.com/passage/?search=proverbs%208:22&version=NLT) > > 22 "The Lord formed me from the beginning, > >          before he created anything else." > > > Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time? How is the identity of Wisdom established as being that of the Son and how is Proverbs 8:22 handled? If it makes a difference, I grew up Wesleyan, so I'd prefer Protestant doctrines although Catholic or Orthodox doctrines would be interesting too.
2012/08/07
[ "https://christianity.stackexchange.com/questions/8946", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
I can tell you who wisdom is [in Sirach](http://www.newadvent.org/bible/sir024.htm)... > > Wisdom shall praise her own self, and shall be honoured in God, and shall glory in the midst of her people, and shall open her mouth in the churches of the most High, and shall glorify herself in the sight of his power, and in the midst of her own people she shall be exalted, and shall be admired in the holy assembly. And in the multitude of the elect she shall have praise, and among the blessed she shall be blessed, saying: I came out of the mouth of the most High, the firstborn before all creatures: (Sirach 24:1-5) > > > It's a lady! Not sure if your doctrines forbid ascribing female characteristic to God, but feminine wisdom and feminine motherliness is palpable throughout the Bible. So I think in the eternal sense (aka the anagogical sense): > > The anagogical sense (Greek: anagoge, "leading"). We can view realities and events in terms of their eternal significance, leading us toward our true homeland: thus the Church on earth is a sign of the heavenly Jerusalem. CCC 117 > > > we can interpret these eternal truths in an eternal fashion. Wisdom gives birth to great ideas and is justifiably considered a woman! Wisdom, like our mother, is our First Teacher. All these things could also be said of the Holy Spirit. --- For addtional Wisdom, check out Sirach's offspring Jesus (no relation) who wrote the [Book of Wisdom](http://www.newadvent.org/cathen/15666a.htm) and for additional confusion, consider the title given to Mary "Seat of Wisdom" and the [Wisdom 7:27](http://www.newadvent.org/bible/wis007.htm#verse27) which says > > The soul of the righteous is the seat of Wisdom. > > > So... Mary, seat of wisdom, Holy Tabernacle of the Lord, model of the Church etc... Models our souls as the place where Wisdom resides.
*Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time?* **Answer** No need to panic, all the commentaries coming from Catholic sources and teaching of the Church Father's are not yet definitive more so defined as a Dogma regarding the definite identification of the Wisdom described in Proverbs8:22. Reading St.Louis De Montfort **"Love of Eternal Wisdom"** is also hard to digest but it is aligned with the Church Father reflection like St.Justin Martyr. But, reading it will still leave room for some doubts if Jesus was really the Wisdom spoken to in that passages. Wisdom is created by God for only one purpose and that is Salvation of Mankind. > > *And thus the paths of those on earth were set right, > and people were taught what pleases you,* > **and were saved by wisdom**.(Wisdom9:18) > > > St.Catherine of Sienna said it simply and profoundly; > > *"All things are pre-ordained towards the salvation of man".* > > > I loved how King Solomon described how God created all things thru His Word but when it comes to forming a man, King Solomon said God created them by His Word & Wisdom. > > *“O God of my ancestors and Lord of mercy, who have made all things by your word,and by your wisdom have formed humankind to have dominion over the creatures you have made, and rule the world in holiness and righteousness, and pronounce judgment in uprightness of soul, give me the wisdom that sits by your throne.* (Wisdom9:1-4) > > > Why God uses Wisdom in forming man? Because man need to be breathe upon in order for it to have a living soul. > > *"Then the LORD God formed man from the dust of the ground and breathed the breath of life into his nostrils, and the man became a living being."* (Genesis1:27) > > > *"For she(Wisdom) is a breath of the power of God, and a pure emanation of the glory of the Almighty;*...(Wisdom7:25) > > > The word "qanah" does not refer to Jesus the Logos because He is "begotten" not created. Jesus existed in the "bosom of the Father". > > *No one has seen God at any time; the only begotten God who is in the bosom of the Father, He has explained Him*.(John1:18) > > > The word "qanah" means to create or birthed was referred to by King Solomon as a Spirit existing beside God meaning, the Wisdom is not internal to God nor cosubstantial with God like the Logos. > > *Then I was constantly[c] at his side. > I was filled with delight day after day, > rejoicing always in his presence, > rejoicing in his whole world > and delighting in mankind.* (Proverbs8:30-31) > > > So, who is the Spirit of Wisdom and how can we properly understand the word "qanah". God in eternity by the love of the Abba Father to the chosen Woman her beloved daughter, and the love of Jesus to His beloved Mother, and the love of the Holy Spirit to Her Spouse had "conceived" in eternity the birth of the "Spirit of Created Wisdom". I said spirit because God is a Spirit and when it gave birth it brought forth a spirit too. > > *Jesus answered, "I tell you the truth, no one can enter the kingdom of God unless he is born of water and the Spirit.* > > > **Flesh gives birth to flesh, but the Spirit gives birth to spirit.**(John3:6) > > > God in eternity had "qanah" or birthed the Spirit of Wisdom, which King Solomon was surprised because Wisdom is the Mother of it all, and Wisdom is the breath that brings life to every creature. > > *I rejoiced in them all, because Wisdom is their leader, > though I had not known that she is their mother.*(Wisdom7:12) > > > In eternity the birth of Spirit of Wisdom, the Mother of all the Living in the order of grace is the First Act of God before He created everything, the Spirit of the Mother of all the living the source of breath must be created first. All creation are connected to Wisdom and human formed had the source of life thru the breath of God which is the Wisdom in Proverbs8:22. In closing, *Jesus the begotten son of God the Logos* existed in eternity at the ***"bosom of the Abba Father"*** while the *"Spirit of Wisdom"* birthed or created by God was ***"beside Him***" meaning Wisdom is external. In eternity, the Most Holy Trinity existed plus the Spirit of Created Wisdom that encompasses the Salvation of Mankind the Divine Plan of God from alpha to omega.
8,946
In general, Wisdom can be (and is, and was) identified as Jesus. However, there is this verse: > > [**Proverbs 8:22 (NLT)**](http://www.biblegateway.com/passage/?search=proverbs%208:22&version=NLT) > > 22 "The Lord formed me from the beginning, > >          before he created anything else." > > > Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time? How is the identity of Wisdom established as being that of the Son and how is Proverbs 8:22 handled? If it makes a difference, I grew up Wesleyan, so I'd prefer Protestant doctrines although Catholic or Orthodox doctrines would be interesting too.
2012/08/07
[ "https://christianity.stackexchange.com/questions/8946", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
Note: Most on-line commentaries seem ascribe this verse to mean the Son of God and the Arian heresy tried to use it as a means for arguing that the Son was created and therefore not eternal. See these commentaries [here](http://bible.cc/proverbs/8-22.htm). --- Anyway, when thinking of the Eternal Son as the wisdom of God we run into the idea that the Son was eternally begotten of the Father. That is, the Son from eternity is the express image and word of the father, proceeding from him. Absolutely considered we can’t say that He was ‘formed’ so it seems when the Bible refers to the Son in this way, it is also looking at this with the eternal counsels of God’s will, in the future plan of incarnating the Son and saving the world, before he ever created it. In this sense the Son is both the ‘power and wisdom of God’, before the creation of the world. > > but to those whom God has called, both Jews and Greeks, Christ the power of God and the wisdom of God. (1 Corinthians 1:24) > > > So when we regard that God was planning from eternity to create and redeem the creation by the Son, the Son is said to be God’s wisdom. It is from eternity, in the thought of this undertaking by the Son, that the verse you mention seems to comprehend. We can see that this wisdom, or counsels of God’s will through His Son, were from eternity: > > 3 Praise be to the God and Father of our Lord Jesus Christ, who has blessed us in the heavenly realms with every spiritual blessing in Christ. 4 For he chose us in him before the creation of the world to be holy and blameless in his sight. In love 5 he predestined us for adoption to sonship through Jesus Christ, in accordance with his pleasure and will— 6 to the praise of his glorious grace, which he has freely given us in the One he loves. (Ephesians 1:3-6) > > >
*Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time?* **Answer** No need to panic, all the commentaries coming from Catholic sources and teaching of the Church Father's are not yet definitive more so defined as a Dogma regarding the definite identification of the Wisdom described in Proverbs8:22. Reading St.Louis De Montfort **"Love of Eternal Wisdom"** is also hard to digest but it is aligned with the Church Father reflection like St.Justin Martyr. But, reading it will still leave room for some doubts if Jesus was really the Wisdom spoken to in that passages. Wisdom is created by God for only one purpose and that is Salvation of Mankind. > > *And thus the paths of those on earth were set right, > and people were taught what pleases you,* > **and were saved by wisdom**.(Wisdom9:18) > > > St.Catherine of Sienna said it simply and profoundly; > > *"All things are pre-ordained towards the salvation of man".* > > > I loved how King Solomon described how God created all things thru His Word but when it comes to forming a man, King Solomon said God created them by His Word & Wisdom. > > *“O God of my ancestors and Lord of mercy, who have made all things by your word,and by your wisdom have formed humankind to have dominion over the creatures you have made, and rule the world in holiness and righteousness, and pronounce judgment in uprightness of soul, give me the wisdom that sits by your throne.* (Wisdom9:1-4) > > > Why God uses Wisdom in forming man? Because man need to be breathe upon in order for it to have a living soul. > > *"Then the LORD God formed man from the dust of the ground and breathed the breath of life into his nostrils, and the man became a living being."* (Genesis1:27) > > > *"For she(Wisdom) is a breath of the power of God, and a pure emanation of the glory of the Almighty;*...(Wisdom7:25) > > > The word "qanah" does not refer to Jesus the Logos because He is "begotten" not created. Jesus existed in the "bosom of the Father". > > *No one has seen God at any time; the only begotten God who is in the bosom of the Father, He has explained Him*.(John1:18) > > > The word "qanah" means to create or birthed was referred to by King Solomon as a Spirit existing beside God meaning, the Wisdom is not internal to God nor cosubstantial with God like the Logos. > > *Then I was constantly[c] at his side. > I was filled with delight day after day, > rejoicing always in his presence, > rejoicing in his whole world > and delighting in mankind.* (Proverbs8:30-31) > > > So, who is the Spirit of Wisdom and how can we properly understand the word "qanah". God in eternity by the love of the Abba Father to the chosen Woman her beloved daughter, and the love of Jesus to His beloved Mother, and the love of the Holy Spirit to Her Spouse had "conceived" in eternity the birth of the "Spirit of Created Wisdom". I said spirit because God is a Spirit and when it gave birth it brought forth a spirit too. > > *Jesus answered, "I tell you the truth, no one can enter the kingdom of God unless he is born of water and the Spirit.* > > > **Flesh gives birth to flesh, but the Spirit gives birth to spirit.**(John3:6) > > > God in eternity had "qanah" or birthed the Spirit of Wisdom, which King Solomon was surprised because Wisdom is the Mother of it all, and Wisdom is the breath that brings life to every creature. > > *I rejoiced in them all, because Wisdom is their leader, > though I had not known that she is their mother.*(Wisdom7:12) > > > In eternity the birth of Spirit of Wisdom, the Mother of all the Living in the order of grace is the First Act of God before He created everything, the Spirit of the Mother of all the living the source of breath must be created first. All creation are connected to Wisdom and human formed had the source of life thru the breath of God which is the Wisdom in Proverbs8:22. In closing, *Jesus the begotten son of God the Logos* existed in eternity at the ***"bosom of the Abba Father"*** while the *"Spirit of Wisdom"* birthed or created by God was ***"beside Him***" meaning Wisdom is external. In eternity, the Most Holy Trinity existed plus the Spirit of Created Wisdom that encompasses the Salvation of Mankind the Divine Plan of God from alpha to omega.
8,946
In general, Wisdom can be (and is, and was) identified as Jesus. However, there is this verse: > > [**Proverbs 8:22 (NLT)**](http://www.biblegateway.com/passage/?search=proverbs%208:22&version=NLT) > > 22 "The Lord formed me from the beginning, > >          before he created anything else." > > > Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time? How is the identity of Wisdom established as being that of the Son and how is Proverbs 8:22 handled? If it makes a difference, I grew up Wesleyan, so I'd prefer Protestant doctrines although Catholic or Orthodox doctrines would be interesting too.
2012/08/07
[ "https://christianity.stackexchange.com/questions/8946", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
There are two common interpretations among Protestants: 1. "Wisdom" refers to the Word of God; that is, Jesus 2. "Wisdom" is the personification of a divine attribute, and perhaps a type of Christ, but should not be understood to be Jesus himself The first view [was widely held by the church fathers](https://christianity.stackexchange.com/a/65951/21576) and several centuries of Protestants. However, in the 20th century the second view became more popular and now dominates Evangelical scholarship. The Word of God: Jesus ====================== The typical patristic understanding of this passage was that Wisdom refers to the Word of God: that is, the Son of God, Jesus. As you note, this raises some questions about the meaning of one key word in verse 22, translated "created," "formed," or "possessed," and this verse was a major battleground in the [Arian controversy](https://en.wikipedia.org/wiki/Arian_controversy). Early Protestants generally followed the patristic understanding, and argue that Jesus's divinity should not be doubted on the basis of this passage. I'll provide a sampling of arguments, but to be clear, the vast majority of early Protestant commentators (particularly prior to the 20th century) take this approach.1 [Matthew Henry](https://en.wikipedia.org/wiki/Matthew_Henry) summarizes this position, noting the very personal characteristics of Wisdom: > > That it is an intelligent and divine person that here speaks seems very plain, and that it is not meant of a mere essential property of the divine nature, for Wisdom here has personal properties and actions and that intelligent divine person can be no other than the Son of God himself.2 > > > Defenders of this view point to New Testament passages referring to Jesus in similar ways, such as [John 1:1](https://www.biblegateway.com/passage/?search=John+1%3A1&version=ESV), [Hebrews 1:3](https://www.biblegateway.com/passage/?search=Hebrews+1%3A3&version=ESV), [1 Peter 1:20](https://www.biblegateway.com/passage/?search=1+Peter+1%3A20&version=ESV) and [Colossians 1:15–18](https://www.biblegateway.com/passage/?search=Colossians+1%3A15-18&version=ESV). But if that's the case, how do Protestants defend against the Arians and others who say that this passage teaches that Jesus was created? The question revolves around the meaning of the Hebrew word [*qanah*](http://biblehub.com/hebrew/7069.htm), which elsewhere in the Old Testament can be translated "get," "acquire," "create," and "possess." Protestants argue for the "possess" translation, and note that the "create" reading would imply that at one point God was without wisdom: > > Not "created me," as the Targum and the Septuagint. [...] [T]his possession [...] denotes the Lord's having, possessing, and enjoying his word and wisdom as his own proper Son.3 > > > Albert Barnes similarly says that there is no "ground for the thought of creation either in the meaning of the root, or in the general usage of the word." His *Notes* go on to point out the logical difficulty of "create": > > What is meant in this passage is that we cannot think of God as ever having been without Wisdom.4 > > > The Personification of a Divine Attribute ========================================= The *Moody Bible Commentary*, citing several recent commentators,5 provides a helpful summary of the alternate position: > > Lady Wisdom here is no more than a personification of the wisdom that the sage has received, a wisdom revealed by God and rooted in His very own character. The context simply does not justify interpretations that go beyond the personification of wisdom here. [...] It is therefore best to say that Lady Wisdom shares similarities with Christ, but Christ is even greater than she. In short, the sage's wisdom is a type of Christ. > > > Others understand the text similarly.6 The *Reformation Study Bible*, though emphasizing Christ as the wisdom of God, still considers the personification of wisdom here to be a "poetic device": > > Although it is premature to see personified wisdom (especially in vv. 22–31) as a direct portrayal of a divine being, there is no doubt that the revelation of Jesus Christ as the wisdom of God shows us the significance of a wisdom that is its own absolute authority. > > > This view was not entirely foreign to writers of the 19th century. Methodist Adam Clarke (1760–1832) critiques the church fathers as finding "allegorical meanings every where," though he too applies Wisdom in verse 3, "She crieth at the gates," to Christ, his apostles, and their successors.7 Summary ======= Each person's understanding of this passage will be influenced by the relative weights placed on the testimony of the church fathers and modern hermeneutics. Early Protestants leaned toward the former, but the latter has gained primacy among Protestants over the last two centuries. Either way, however, Protestants have carefully argued that the text does not challenge the divinity of Christ. --- **References:** 1. [Geneva Study Bible, Wesley, Coke, Poole, Scofield. Also Catholic Haydock.](http://www.studylight.org/commentary/proverbs/8-22.html) 2. Henry, [*Commentary on the Whole Bible, III*](http://www.ccel.org/ccel/henry/mhc3.Prov.ix.html) 3. Gill, [*Exposition of the Whole Bible*](http://www.studylight.org/commentaries/geb/view.cgi?bk=19&ch=8#45). Cf. [James Coffman](http://www.studylight.org/commentaries/bcc/view.cgi?bk=pr&ch=8#22); though not a defender of this view, he writes at length on how to properly translate this word. 4. Barnes, [*Notes*](http://www.studylight.org/commentaries/bnb/view.cgi?bk=pr&ch=8#14) 5. Kidner ([*Proverbs*](https://books.google.com/books?id=u00jCgAAQBAJ)), Longman ([*Proverbs*](https://books.google.com/books?id=T9prN-7WqYAC)), and Waltke ([*Book of Proverbs 1-15*](https://books.google.com/books?id=kboLy_NBxc4C)), among others. 6. *ESV Study Bible*, *NIV Study Bible*, and [Keil & Delitzsch](http://www.studylight.org/commentaries/kdo/view.cgi?bk=pr&ch=8#1-3), for example. 7. Clarke, [*Commentary*](http://www.studylight.org/commentaries/acc/view.cgi?bk=19&ch=8#22)
Note: Most on-line commentaries seem ascribe this verse to mean the Son of God and the Arian heresy tried to use it as a means for arguing that the Son was created and therefore not eternal. See these commentaries [here](http://bible.cc/proverbs/8-22.htm). --- Anyway, when thinking of the Eternal Son as the wisdom of God we run into the idea that the Son was eternally begotten of the Father. That is, the Son from eternity is the express image and word of the father, proceeding from him. Absolutely considered we can’t say that He was ‘formed’ so it seems when the Bible refers to the Son in this way, it is also looking at this with the eternal counsels of God’s will, in the future plan of incarnating the Son and saving the world, before he ever created it. In this sense the Son is both the ‘power and wisdom of God’, before the creation of the world. > > but to those whom God has called, both Jews and Greeks, Christ the power of God and the wisdom of God. (1 Corinthians 1:24) > > > So when we regard that God was planning from eternity to create and redeem the creation by the Son, the Son is said to be God’s wisdom. It is from eternity, in the thought of this undertaking by the Son, that the verse you mention seems to comprehend. We can see that this wisdom, or counsels of God’s will through His Son, were from eternity: > > 3 Praise be to the God and Father of our Lord Jesus Christ, who has blessed us in the heavenly realms with every spiritual blessing in Christ. 4 For he chose us in him before the creation of the world to be holy and blameless in his sight. In love 5 he predestined us for adoption to sonship through Jesus Christ, in accordance with his pleasure and will— 6 to the praise of his glorious grace, which he has freely given us in the One he loves. (Ephesians 1:3-6) > > >
8,946
In general, Wisdom can be (and is, and was) identified as Jesus. However, there is this verse: > > [**Proverbs 8:22 (NLT)**](http://www.biblegateway.com/passage/?search=proverbs%208:22&version=NLT) > > 22 "The Lord formed me from the beginning, > >          before he created anything else." > > > Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time? How is the identity of Wisdom established as being that of the Son and how is Proverbs 8:22 handled? If it makes a difference, I grew up Wesleyan, so I'd prefer Protestant doctrines although Catholic or Orthodox doctrines would be interesting too.
2012/08/07
[ "https://christianity.stackexchange.com/questions/8946", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
"Wisdom" in the context of these verses isn't anybody. It's wisdom, as you or I would understand the word, literally, but in this particular context, Solomon is Anthropomorphizing the character trait of wisdom. I've never once seen a commentary, or heard a message that gives any indication that "Wisdom" in these passages means anything else. That Solomon would Anthropomorphize wisdom isn't surprising. The Proverbs have a very poetic style, almost equaling that of the Psalms. And Solomon valued wisdom. When God offered to give Solomon anything he wanted, Solomon asked for wisdom. ([1 Kings Chapter 3](http://www.biblegateway.com/passage/?search=1%20Kings%203&version=KJV)) It's quite common in literature to use anthropomorphism when describing non-living objects, or even concepts. In this particular proverb, Solomon is simply expressing the importance of, and value of wisdom using poetic language.
This article by CRI is useful: <https://www.equip.org/article/who-is-wisdom-in-proverbs-8/> They make the case that the literary form of encomium is being used. An encomium is the praise of a character quality, offered so as to persuade others to imitate it. It is poetic and it is fiction. It uses personification. Another example of an encomium in the Bible is 1 Corinthians 13, about love. They list some defining elements of an encomium: > > The writer of an encomium conducts the praise by using a standard set > of literary motifs (elements): (1) introduction to the subject, (2) > the distinguished and ancient ancestry of the subject, (3) a list of > the praiseworthy acts and qualities of the subject, (4) the > indispensable and/or superior nature of the subject, and (5) a > conclusion urging the reader to emulate the subject. > > > Thus this passage does not refer to Jesus at all, so cannot be used to argue (as the article says the Jehovah's Witnesses do) that Christ is a created being.
8,946
In general, Wisdom can be (and is, and was) identified as Jesus. However, there is this verse: > > [**Proverbs 8:22 (NLT)**](http://www.biblegateway.com/passage/?search=proverbs%208:22&version=NLT) > > 22 "The Lord formed me from the beginning, > >          before he created anything else." > > > Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time? How is the identity of Wisdom established as being that of the Son and how is Proverbs 8:22 handled? If it makes a difference, I grew up Wesleyan, so I'd prefer Protestant doctrines although Catholic or Orthodox doctrines would be interesting too.
2012/08/07
[ "https://christianity.stackexchange.com/questions/8946", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
There are two common interpretations among Protestants: 1. "Wisdom" refers to the Word of God; that is, Jesus 2. "Wisdom" is the personification of a divine attribute, and perhaps a type of Christ, but should not be understood to be Jesus himself The first view [was widely held by the church fathers](https://christianity.stackexchange.com/a/65951/21576) and several centuries of Protestants. However, in the 20th century the second view became more popular and now dominates Evangelical scholarship. The Word of God: Jesus ====================== The typical patristic understanding of this passage was that Wisdom refers to the Word of God: that is, the Son of God, Jesus. As you note, this raises some questions about the meaning of one key word in verse 22, translated "created," "formed," or "possessed," and this verse was a major battleground in the [Arian controversy](https://en.wikipedia.org/wiki/Arian_controversy). Early Protestants generally followed the patristic understanding, and argue that Jesus's divinity should not be doubted on the basis of this passage. I'll provide a sampling of arguments, but to be clear, the vast majority of early Protestant commentators (particularly prior to the 20th century) take this approach.1 [Matthew Henry](https://en.wikipedia.org/wiki/Matthew_Henry) summarizes this position, noting the very personal characteristics of Wisdom: > > That it is an intelligent and divine person that here speaks seems very plain, and that it is not meant of a mere essential property of the divine nature, for Wisdom here has personal properties and actions and that intelligent divine person can be no other than the Son of God himself.2 > > > Defenders of this view point to New Testament passages referring to Jesus in similar ways, such as [John 1:1](https://www.biblegateway.com/passage/?search=John+1%3A1&version=ESV), [Hebrews 1:3](https://www.biblegateway.com/passage/?search=Hebrews+1%3A3&version=ESV), [1 Peter 1:20](https://www.biblegateway.com/passage/?search=1+Peter+1%3A20&version=ESV) and [Colossians 1:15–18](https://www.biblegateway.com/passage/?search=Colossians+1%3A15-18&version=ESV). But if that's the case, how do Protestants defend against the Arians and others who say that this passage teaches that Jesus was created? The question revolves around the meaning of the Hebrew word [*qanah*](http://biblehub.com/hebrew/7069.htm), which elsewhere in the Old Testament can be translated "get," "acquire," "create," and "possess." Protestants argue for the "possess" translation, and note that the "create" reading would imply that at one point God was without wisdom: > > Not "created me," as the Targum and the Septuagint. [...] [T]his possession [...] denotes the Lord's having, possessing, and enjoying his word and wisdom as his own proper Son.3 > > > Albert Barnes similarly says that there is no "ground for the thought of creation either in the meaning of the root, or in the general usage of the word." His *Notes* go on to point out the logical difficulty of "create": > > What is meant in this passage is that we cannot think of God as ever having been without Wisdom.4 > > > The Personification of a Divine Attribute ========================================= The *Moody Bible Commentary*, citing several recent commentators,5 provides a helpful summary of the alternate position: > > Lady Wisdom here is no more than a personification of the wisdom that the sage has received, a wisdom revealed by God and rooted in His very own character. The context simply does not justify interpretations that go beyond the personification of wisdom here. [...] It is therefore best to say that Lady Wisdom shares similarities with Christ, but Christ is even greater than she. In short, the sage's wisdom is a type of Christ. > > > Others understand the text similarly.6 The *Reformation Study Bible*, though emphasizing Christ as the wisdom of God, still considers the personification of wisdom here to be a "poetic device": > > Although it is premature to see personified wisdom (especially in vv. 22–31) as a direct portrayal of a divine being, there is no doubt that the revelation of Jesus Christ as the wisdom of God shows us the significance of a wisdom that is its own absolute authority. > > > This view was not entirely foreign to writers of the 19th century. Methodist Adam Clarke (1760–1832) critiques the church fathers as finding "allegorical meanings every where," though he too applies Wisdom in verse 3, "She crieth at the gates," to Christ, his apostles, and their successors.7 Summary ======= Each person's understanding of this passage will be influenced by the relative weights placed on the testimony of the church fathers and modern hermeneutics. Early Protestants leaned toward the former, but the latter has gained primacy among Protestants over the last two centuries. Either way, however, Protestants have carefully argued that the text does not challenge the divinity of Christ. --- **References:** 1. [Geneva Study Bible, Wesley, Coke, Poole, Scofield. Also Catholic Haydock.](http://www.studylight.org/commentary/proverbs/8-22.html) 2. Henry, [*Commentary on the Whole Bible, III*](http://www.ccel.org/ccel/henry/mhc3.Prov.ix.html) 3. Gill, [*Exposition of the Whole Bible*](http://www.studylight.org/commentaries/geb/view.cgi?bk=19&ch=8#45). Cf. [James Coffman](http://www.studylight.org/commentaries/bcc/view.cgi?bk=pr&ch=8#22); though not a defender of this view, he writes at length on how to properly translate this word. 4. Barnes, [*Notes*](http://www.studylight.org/commentaries/bnb/view.cgi?bk=pr&ch=8#14) 5. Kidner ([*Proverbs*](https://books.google.com/books?id=u00jCgAAQBAJ)), Longman ([*Proverbs*](https://books.google.com/books?id=T9prN-7WqYAC)), and Waltke ([*Book of Proverbs 1-15*](https://books.google.com/books?id=kboLy_NBxc4C)), among others. 6. *ESV Study Bible*, *NIV Study Bible*, and [Keil & Delitzsch](http://www.studylight.org/commentaries/kdo/view.cgi?bk=pr&ch=8#1-3), for example. 7. Clarke, [*Commentary*](http://www.studylight.org/commentaries/acc/view.cgi?bk=19&ch=8#22)
I can tell you who wisdom is [in Sirach](http://www.newadvent.org/bible/sir024.htm)... > > Wisdom shall praise her own self, and shall be honoured in God, and shall glory in the midst of her people, and shall open her mouth in the churches of the most High, and shall glorify herself in the sight of his power, and in the midst of her own people she shall be exalted, and shall be admired in the holy assembly. And in the multitude of the elect she shall have praise, and among the blessed she shall be blessed, saying: I came out of the mouth of the most High, the firstborn before all creatures: (Sirach 24:1-5) > > > It's a lady! Not sure if your doctrines forbid ascribing female characteristic to God, but feminine wisdom and feminine motherliness is palpable throughout the Bible. So I think in the eternal sense (aka the anagogical sense): > > The anagogical sense (Greek: anagoge, "leading"). We can view realities and events in terms of their eternal significance, leading us toward our true homeland: thus the Church on earth is a sign of the heavenly Jerusalem. CCC 117 > > > we can interpret these eternal truths in an eternal fashion. Wisdom gives birth to great ideas and is justifiably considered a woman! Wisdom, like our mother, is our First Teacher. All these things could also be said of the Holy Spirit. --- For addtional Wisdom, check out Sirach's offspring Jesus (no relation) who wrote the [Book of Wisdom](http://www.newadvent.org/cathen/15666a.htm) and for additional confusion, consider the title given to Mary "Seat of Wisdom" and the [Wisdom 7:27](http://www.newadvent.org/bible/wis007.htm#verse27) which says > > The soul of the righteous is the seat of Wisdom. > > > So... Mary, seat of wisdom, Holy Tabernacle of the Lord, model of the Church etc... Models our souls as the place where Wisdom resides.
8,946
In general, Wisdom can be (and is, and was) identified as Jesus. However, there is this verse: > > [**Proverbs 8:22 (NLT)**](http://www.biblegateway.com/passage/?search=proverbs%208:22&version=NLT) > > 22 "The Lord formed me from the beginning, > >          before he created anything else." > > > Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time? How is the identity of Wisdom established as being that of the Son and how is Proverbs 8:22 handled? If it makes a difference, I grew up Wesleyan, so I'd prefer Protestant doctrines although Catholic or Orthodox doctrines would be interesting too.
2012/08/07
[ "https://christianity.stackexchange.com/questions/8946", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
There are two common interpretations among Protestants: 1. "Wisdom" refers to the Word of God; that is, Jesus 2. "Wisdom" is the personification of a divine attribute, and perhaps a type of Christ, but should not be understood to be Jesus himself The first view [was widely held by the church fathers](https://christianity.stackexchange.com/a/65951/21576) and several centuries of Protestants. However, in the 20th century the second view became more popular and now dominates Evangelical scholarship. The Word of God: Jesus ====================== The typical patristic understanding of this passage was that Wisdom refers to the Word of God: that is, the Son of God, Jesus. As you note, this raises some questions about the meaning of one key word in verse 22, translated "created," "formed," or "possessed," and this verse was a major battleground in the [Arian controversy](https://en.wikipedia.org/wiki/Arian_controversy). Early Protestants generally followed the patristic understanding, and argue that Jesus's divinity should not be doubted on the basis of this passage. I'll provide a sampling of arguments, but to be clear, the vast majority of early Protestant commentators (particularly prior to the 20th century) take this approach.1 [Matthew Henry](https://en.wikipedia.org/wiki/Matthew_Henry) summarizes this position, noting the very personal characteristics of Wisdom: > > That it is an intelligent and divine person that here speaks seems very plain, and that it is not meant of a mere essential property of the divine nature, for Wisdom here has personal properties and actions and that intelligent divine person can be no other than the Son of God himself.2 > > > Defenders of this view point to New Testament passages referring to Jesus in similar ways, such as [John 1:1](https://www.biblegateway.com/passage/?search=John+1%3A1&version=ESV), [Hebrews 1:3](https://www.biblegateway.com/passage/?search=Hebrews+1%3A3&version=ESV), [1 Peter 1:20](https://www.biblegateway.com/passage/?search=1+Peter+1%3A20&version=ESV) and [Colossians 1:15–18](https://www.biblegateway.com/passage/?search=Colossians+1%3A15-18&version=ESV). But if that's the case, how do Protestants defend against the Arians and others who say that this passage teaches that Jesus was created? The question revolves around the meaning of the Hebrew word [*qanah*](http://biblehub.com/hebrew/7069.htm), which elsewhere in the Old Testament can be translated "get," "acquire," "create," and "possess." Protestants argue for the "possess" translation, and note that the "create" reading would imply that at one point God was without wisdom: > > Not "created me," as the Targum and the Septuagint. [...] [T]his possession [...] denotes the Lord's having, possessing, and enjoying his word and wisdom as his own proper Son.3 > > > Albert Barnes similarly says that there is no "ground for the thought of creation either in the meaning of the root, or in the general usage of the word." His *Notes* go on to point out the logical difficulty of "create": > > What is meant in this passage is that we cannot think of God as ever having been without Wisdom.4 > > > The Personification of a Divine Attribute ========================================= The *Moody Bible Commentary*, citing several recent commentators,5 provides a helpful summary of the alternate position: > > Lady Wisdom here is no more than a personification of the wisdom that the sage has received, a wisdom revealed by God and rooted in His very own character. The context simply does not justify interpretations that go beyond the personification of wisdom here. [...] It is therefore best to say that Lady Wisdom shares similarities with Christ, but Christ is even greater than she. In short, the sage's wisdom is a type of Christ. > > > Others understand the text similarly.6 The *Reformation Study Bible*, though emphasizing Christ as the wisdom of God, still considers the personification of wisdom here to be a "poetic device": > > Although it is premature to see personified wisdom (especially in vv. 22–31) as a direct portrayal of a divine being, there is no doubt that the revelation of Jesus Christ as the wisdom of God shows us the significance of a wisdom that is its own absolute authority. > > > This view was not entirely foreign to writers of the 19th century. Methodist Adam Clarke (1760–1832) critiques the church fathers as finding "allegorical meanings every where," though he too applies Wisdom in verse 3, "She crieth at the gates," to Christ, his apostles, and their successors.7 Summary ======= Each person's understanding of this passage will be influenced by the relative weights placed on the testimony of the church fathers and modern hermeneutics. Early Protestants leaned toward the former, but the latter has gained primacy among Protestants over the last two centuries. Either way, however, Protestants have carefully argued that the text does not challenge the divinity of Christ. --- **References:** 1. [Geneva Study Bible, Wesley, Coke, Poole, Scofield. Also Catholic Haydock.](http://www.studylight.org/commentary/proverbs/8-22.html) 2. Henry, [*Commentary on the Whole Bible, III*](http://www.ccel.org/ccel/henry/mhc3.Prov.ix.html) 3. Gill, [*Exposition of the Whole Bible*](http://www.studylight.org/commentaries/geb/view.cgi?bk=19&ch=8#45). Cf. [James Coffman](http://www.studylight.org/commentaries/bcc/view.cgi?bk=pr&ch=8#22); though not a defender of this view, he writes at length on how to properly translate this word. 4. Barnes, [*Notes*](http://www.studylight.org/commentaries/bnb/view.cgi?bk=pr&ch=8#14) 5. Kidner ([*Proverbs*](https://books.google.com/books?id=u00jCgAAQBAJ)), Longman ([*Proverbs*](https://books.google.com/books?id=T9prN-7WqYAC)), and Waltke ([*Book of Proverbs 1-15*](https://books.google.com/books?id=kboLy_NBxc4C)), among others. 6. *ESV Study Bible*, *NIV Study Bible*, and [Keil & Delitzsch](http://www.studylight.org/commentaries/kdo/view.cgi?bk=pr&ch=8#1-3), for example. 7. Clarke, [*Commentary*](http://www.studylight.org/commentaries/acc/view.cgi?bk=19&ch=8#22)
*Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time?* **Answer** No need to panic, all the commentaries coming from Catholic sources and teaching of the Church Father's are not yet definitive more so defined as a Dogma regarding the definite identification of the Wisdom described in Proverbs8:22. Reading St.Louis De Montfort **"Love of Eternal Wisdom"** is also hard to digest but it is aligned with the Church Father reflection like St.Justin Martyr. But, reading it will still leave room for some doubts if Jesus was really the Wisdom spoken to in that passages. Wisdom is created by God for only one purpose and that is Salvation of Mankind. > > *And thus the paths of those on earth were set right, > and people were taught what pleases you,* > **and were saved by wisdom**.(Wisdom9:18) > > > St.Catherine of Sienna said it simply and profoundly; > > *"All things are pre-ordained towards the salvation of man".* > > > I loved how King Solomon described how God created all things thru His Word but when it comes to forming a man, King Solomon said God created them by His Word & Wisdom. > > *“O God of my ancestors and Lord of mercy, who have made all things by your word,and by your wisdom have formed humankind to have dominion over the creatures you have made, and rule the world in holiness and righteousness, and pronounce judgment in uprightness of soul, give me the wisdom that sits by your throne.* (Wisdom9:1-4) > > > Why God uses Wisdom in forming man? Because man need to be breathe upon in order for it to have a living soul. > > *"Then the LORD God formed man from the dust of the ground and breathed the breath of life into his nostrils, and the man became a living being."* (Genesis1:27) > > > *"For she(Wisdom) is a breath of the power of God, and a pure emanation of the glory of the Almighty;*...(Wisdom7:25) > > > The word "qanah" does not refer to Jesus the Logos because He is "begotten" not created. Jesus existed in the "bosom of the Father". > > *No one has seen God at any time; the only begotten God who is in the bosom of the Father, He has explained Him*.(John1:18) > > > The word "qanah" means to create or birthed was referred to by King Solomon as a Spirit existing beside God meaning, the Wisdom is not internal to God nor cosubstantial with God like the Logos. > > *Then I was constantly[c] at his side. > I was filled with delight day after day, > rejoicing always in his presence, > rejoicing in his whole world > and delighting in mankind.* (Proverbs8:30-31) > > > So, who is the Spirit of Wisdom and how can we properly understand the word "qanah". God in eternity by the love of the Abba Father to the chosen Woman her beloved daughter, and the love of Jesus to His beloved Mother, and the love of the Holy Spirit to Her Spouse had "conceived" in eternity the birth of the "Spirit of Created Wisdom". I said spirit because God is a Spirit and when it gave birth it brought forth a spirit too. > > *Jesus answered, "I tell you the truth, no one can enter the kingdom of God unless he is born of water and the Spirit.* > > > **Flesh gives birth to flesh, but the Spirit gives birth to spirit.**(John3:6) > > > God in eternity had "qanah" or birthed the Spirit of Wisdom, which King Solomon was surprised because Wisdom is the Mother of it all, and Wisdom is the breath that brings life to every creature. > > *I rejoiced in them all, because Wisdom is their leader, > though I had not known that she is their mother.*(Wisdom7:12) > > > In eternity the birth of Spirit of Wisdom, the Mother of all the Living in the order of grace is the First Act of God before He created everything, the Spirit of the Mother of all the living the source of breath must be created first. All creation are connected to Wisdom and human formed had the source of life thru the breath of God which is the Wisdom in Proverbs8:22. In closing, *Jesus the begotten son of God the Logos* existed in eternity at the ***"bosom of the Abba Father"*** while the *"Spirit of Wisdom"* birthed or created by God was ***"beside Him***" meaning Wisdom is external. In eternity, the Most Holy Trinity existed plus the Spirit of Created Wisdom that encompasses the Salvation of Mankind the Divine Plan of God from alpha to omega.
8,946
In general, Wisdom can be (and is, and was) identified as Jesus. However, there is this verse: > > [**Proverbs 8:22 (NLT)**](http://www.biblegateway.com/passage/?search=proverbs%208:22&version=NLT) > > 22 "The Lord formed me from the beginning, > >          before he created anything else." > > > Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time? How is the identity of Wisdom established as being that of the Son and how is Proverbs 8:22 handled? If it makes a difference, I grew up Wesleyan, so I'd prefer Protestant doctrines although Catholic or Orthodox doctrines would be interesting too.
2012/08/07
[ "https://christianity.stackexchange.com/questions/8946", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
There are two common interpretations among Protestants: 1. "Wisdom" refers to the Word of God; that is, Jesus 2. "Wisdom" is the personification of a divine attribute, and perhaps a type of Christ, but should not be understood to be Jesus himself The first view [was widely held by the church fathers](https://christianity.stackexchange.com/a/65951/21576) and several centuries of Protestants. However, in the 20th century the second view became more popular and now dominates Evangelical scholarship. The Word of God: Jesus ====================== The typical patristic understanding of this passage was that Wisdom refers to the Word of God: that is, the Son of God, Jesus. As you note, this raises some questions about the meaning of one key word in verse 22, translated "created," "formed," or "possessed," and this verse was a major battleground in the [Arian controversy](https://en.wikipedia.org/wiki/Arian_controversy). Early Protestants generally followed the patristic understanding, and argue that Jesus's divinity should not be doubted on the basis of this passage. I'll provide a sampling of arguments, but to be clear, the vast majority of early Protestant commentators (particularly prior to the 20th century) take this approach.1 [Matthew Henry](https://en.wikipedia.org/wiki/Matthew_Henry) summarizes this position, noting the very personal characteristics of Wisdom: > > That it is an intelligent and divine person that here speaks seems very plain, and that it is not meant of a mere essential property of the divine nature, for Wisdom here has personal properties and actions and that intelligent divine person can be no other than the Son of God himself.2 > > > Defenders of this view point to New Testament passages referring to Jesus in similar ways, such as [John 1:1](https://www.biblegateway.com/passage/?search=John+1%3A1&version=ESV), [Hebrews 1:3](https://www.biblegateway.com/passage/?search=Hebrews+1%3A3&version=ESV), [1 Peter 1:20](https://www.biblegateway.com/passage/?search=1+Peter+1%3A20&version=ESV) and [Colossians 1:15–18](https://www.biblegateway.com/passage/?search=Colossians+1%3A15-18&version=ESV). But if that's the case, how do Protestants defend against the Arians and others who say that this passage teaches that Jesus was created? The question revolves around the meaning of the Hebrew word [*qanah*](http://biblehub.com/hebrew/7069.htm), which elsewhere in the Old Testament can be translated "get," "acquire," "create," and "possess." Protestants argue for the "possess" translation, and note that the "create" reading would imply that at one point God was without wisdom: > > Not "created me," as the Targum and the Septuagint. [...] [T]his possession [...] denotes the Lord's having, possessing, and enjoying his word and wisdom as his own proper Son.3 > > > Albert Barnes similarly says that there is no "ground for the thought of creation either in the meaning of the root, or in the general usage of the word." His *Notes* go on to point out the logical difficulty of "create": > > What is meant in this passage is that we cannot think of God as ever having been without Wisdom.4 > > > The Personification of a Divine Attribute ========================================= The *Moody Bible Commentary*, citing several recent commentators,5 provides a helpful summary of the alternate position: > > Lady Wisdom here is no more than a personification of the wisdom that the sage has received, a wisdom revealed by God and rooted in His very own character. The context simply does not justify interpretations that go beyond the personification of wisdom here. [...] It is therefore best to say that Lady Wisdom shares similarities with Christ, but Christ is even greater than she. In short, the sage's wisdom is a type of Christ. > > > Others understand the text similarly.6 The *Reformation Study Bible*, though emphasizing Christ as the wisdom of God, still considers the personification of wisdom here to be a "poetic device": > > Although it is premature to see personified wisdom (especially in vv. 22–31) as a direct portrayal of a divine being, there is no doubt that the revelation of Jesus Christ as the wisdom of God shows us the significance of a wisdom that is its own absolute authority. > > > This view was not entirely foreign to writers of the 19th century. Methodist Adam Clarke (1760–1832) critiques the church fathers as finding "allegorical meanings every where," though he too applies Wisdom in verse 3, "She crieth at the gates," to Christ, his apostles, and their successors.7 Summary ======= Each person's understanding of this passage will be influenced by the relative weights placed on the testimony of the church fathers and modern hermeneutics. Early Protestants leaned toward the former, but the latter has gained primacy among Protestants over the last two centuries. Either way, however, Protestants have carefully argued that the text does not challenge the divinity of Christ. --- **References:** 1. [Geneva Study Bible, Wesley, Coke, Poole, Scofield. Also Catholic Haydock.](http://www.studylight.org/commentary/proverbs/8-22.html) 2. Henry, [*Commentary on the Whole Bible, III*](http://www.ccel.org/ccel/henry/mhc3.Prov.ix.html) 3. Gill, [*Exposition of the Whole Bible*](http://www.studylight.org/commentaries/geb/view.cgi?bk=19&ch=8#45). Cf. [James Coffman](http://www.studylight.org/commentaries/bcc/view.cgi?bk=pr&ch=8#22); though not a defender of this view, he writes at length on how to properly translate this word. 4. Barnes, [*Notes*](http://www.studylight.org/commentaries/bnb/view.cgi?bk=pr&ch=8#14) 5. Kidner ([*Proverbs*](https://books.google.com/books?id=u00jCgAAQBAJ)), Longman ([*Proverbs*](https://books.google.com/books?id=T9prN-7WqYAC)), and Waltke ([*Book of Proverbs 1-15*](https://books.google.com/books?id=kboLy_NBxc4C)), among others. 6. *ESV Study Bible*, *NIV Study Bible*, and [Keil & Delitzsch](http://www.studylight.org/commentaries/kdo/view.cgi?bk=pr&ch=8#1-3), for example. 7. Clarke, [*Commentary*](http://www.studylight.org/commentaries/acc/view.cgi?bk=19&ch=8#22)
This article by CRI is useful: <https://www.equip.org/article/who-is-wisdom-in-proverbs-8/> They make the case that the literary form of encomium is being used. An encomium is the praise of a character quality, offered so as to persuade others to imitate it. It is poetic and it is fiction. It uses personification. Another example of an encomium in the Bible is 1 Corinthians 13, about love. They list some defining elements of an encomium: > > The writer of an encomium conducts the praise by using a standard set > of literary motifs (elements): (1) introduction to the subject, (2) > the distinguished and ancient ancestry of the subject, (3) a list of > the praiseworthy acts and qualities of the subject, (4) the > indispensable and/or superior nature of the subject, and (5) a > conclusion urging the reader to emulate the subject. > > > Thus this passage does not refer to Jesus at all, so cannot be used to argue (as the article says the Jehovah's Witnesses do) that Christ is a created being.
8,946
In general, Wisdom can be (and is, and was) identified as Jesus. However, there is this verse: > > [**Proverbs 8:22 (NLT)**](http://www.biblegateway.com/passage/?search=proverbs%208:22&version=NLT) > > 22 "The Lord formed me from the beginning, > >          before he created anything else." > > > Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time? How is the identity of Wisdom established as being that of the Son and how is Proverbs 8:22 handled? If it makes a difference, I grew up Wesleyan, so I'd prefer Protestant doctrines although Catholic or Orthodox doctrines would be interesting too.
2012/08/07
[ "https://christianity.stackexchange.com/questions/8946", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
I can tell you who wisdom is [in Sirach](http://www.newadvent.org/bible/sir024.htm)... > > Wisdom shall praise her own self, and shall be honoured in God, and shall glory in the midst of her people, and shall open her mouth in the churches of the most High, and shall glorify herself in the sight of his power, and in the midst of her own people she shall be exalted, and shall be admired in the holy assembly. And in the multitude of the elect she shall have praise, and among the blessed she shall be blessed, saying: I came out of the mouth of the most High, the firstborn before all creatures: (Sirach 24:1-5) > > > It's a lady! Not sure if your doctrines forbid ascribing female characteristic to God, but feminine wisdom and feminine motherliness is palpable throughout the Bible. So I think in the eternal sense (aka the anagogical sense): > > The anagogical sense (Greek: anagoge, "leading"). We can view realities and events in terms of their eternal significance, leading us toward our true homeland: thus the Church on earth is a sign of the heavenly Jerusalem. CCC 117 > > > we can interpret these eternal truths in an eternal fashion. Wisdom gives birth to great ideas and is justifiably considered a woman! Wisdom, like our mother, is our First Teacher. All these things could also be said of the Holy Spirit. --- For addtional Wisdom, check out Sirach's offspring Jesus (no relation) who wrote the [Book of Wisdom](http://www.newadvent.org/cathen/15666a.htm) and for additional confusion, consider the title given to Mary "Seat of Wisdom" and the [Wisdom 7:27](http://www.newadvent.org/bible/wis007.htm#verse27) which says > > The soul of the righteous is the seat of Wisdom. > > > So... Mary, seat of wisdom, Holy Tabernacle of the Lord, model of the Church etc... Models our souls as the place where Wisdom resides.
This article by CRI is useful: <https://www.equip.org/article/who-is-wisdom-in-proverbs-8/> They make the case that the literary form of encomium is being used. An encomium is the praise of a character quality, offered so as to persuade others to imitate it. It is poetic and it is fiction. It uses personification. Another example of an encomium in the Bible is 1 Corinthians 13, about love. They list some defining elements of an encomium: > > The writer of an encomium conducts the praise by using a standard set > of literary motifs (elements): (1) introduction to the subject, (2) > the distinguished and ancient ancestry of the subject, (3) a list of > the praiseworthy acts and qualities of the subject, (4) the > indispensable and/or superior nature of the subject, and (5) a > conclusion urging the reader to emulate the subject. > > > Thus this passage does not refer to Jesus at all, so cannot be used to argue (as the article says the Jehovah's Witnesses do) that Christ is a created being.
8,946
In general, Wisdom can be (and is, and was) identified as Jesus. However, there is this verse: > > [**Proverbs 8:22 (NLT)**](http://www.biblegateway.com/passage/?search=proverbs%208:22&version=NLT) > > 22 "The Lord formed me from the beginning, > >          before he created anything else." > > > Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time? How is the identity of Wisdom established as being that of the Son and how is Proverbs 8:22 handled? If it makes a difference, I grew up Wesleyan, so I'd prefer Protestant doctrines although Catholic or Orthodox doctrines would be interesting too.
2012/08/07
[ "https://christianity.stackexchange.com/questions/8946", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
"Wisdom" in the context of these verses isn't anybody. It's wisdom, as you or I would understand the word, literally, but in this particular context, Solomon is Anthropomorphizing the character trait of wisdom. I've never once seen a commentary, or heard a message that gives any indication that "Wisdom" in these passages means anything else. That Solomon would Anthropomorphize wisdom isn't surprising. The Proverbs have a very poetic style, almost equaling that of the Psalms. And Solomon valued wisdom. When God offered to give Solomon anything he wanted, Solomon asked for wisdom. ([1 Kings Chapter 3](http://www.biblegateway.com/passage/?search=1%20Kings%203&version=KJV)) It's quite common in literature to use anthropomorphism when describing non-living objects, or even concepts. In this particular proverb, Solomon is simply expressing the importance of, and value of wisdom using poetic language.
*Hold on a moment...I thought God the Son wasn't created, having coexisted with God the Father since before time?* **Answer** No need to panic, all the commentaries coming from Catholic sources and teaching of the Church Father's are not yet definitive more so defined as a Dogma regarding the definite identification of the Wisdom described in Proverbs8:22. Reading St.Louis De Montfort **"Love of Eternal Wisdom"** is also hard to digest but it is aligned with the Church Father reflection like St.Justin Martyr. But, reading it will still leave room for some doubts if Jesus was really the Wisdom spoken to in that passages. Wisdom is created by God for only one purpose and that is Salvation of Mankind. > > *And thus the paths of those on earth were set right, > and people were taught what pleases you,* > **and were saved by wisdom**.(Wisdom9:18) > > > St.Catherine of Sienna said it simply and profoundly; > > *"All things are pre-ordained towards the salvation of man".* > > > I loved how King Solomon described how God created all things thru His Word but when it comes to forming a man, King Solomon said God created them by His Word & Wisdom. > > *“O God of my ancestors and Lord of mercy, who have made all things by your word,and by your wisdom have formed humankind to have dominion over the creatures you have made, and rule the world in holiness and righteousness, and pronounce judgment in uprightness of soul, give me the wisdom that sits by your throne.* (Wisdom9:1-4) > > > Why God uses Wisdom in forming man? Because man need to be breathe upon in order for it to have a living soul. > > *"Then the LORD God formed man from the dust of the ground and breathed the breath of life into his nostrils, and the man became a living being."* (Genesis1:27) > > > *"For she(Wisdom) is a breath of the power of God, and a pure emanation of the glory of the Almighty;*...(Wisdom7:25) > > > The word "qanah" does not refer to Jesus the Logos because He is "begotten" not created. Jesus existed in the "bosom of the Father". > > *No one has seen God at any time; the only begotten God who is in the bosom of the Father, He has explained Him*.(John1:18) > > > The word "qanah" means to create or birthed was referred to by King Solomon as a Spirit existing beside God meaning, the Wisdom is not internal to God nor cosubstantial with God like the Logos. > > *Then I was constantly[c] at his side. > I was filled with delight day after day, > rejoicing always in his presence, > rejoicing in his whole world > and delighting in mankind.* (Proverbs8:30-31) > > > So, who is the Spirit of Wisdom and how can we properly understand the word "qanah". God in eternity by the love of the Abba Father to the chosen Woman her beloved daughter, and the love of Jesus to His beloved Mother, and the love of the Holy Spirit to Her Spouse had "conceived" in eternity the birth of the "Spirit of Created Wisdom". I said spirit because God is a Spirit and when it gave birth it brought forth a spirit too. > > *Jesus answered, "I tell you the truth, no one can enter the kingdom of God unless he is born of water and the Spirit.* > > > **Flesh gives birth to flesh, but the Spirit gives birth to spirit.**(John3:6) > > > God in eternity had "qanah" or birthed the Spirit of Wisdom, which King Solomon was surprised because Wisdom is the Mother of it all, and Wisdom is the breath that brings life to every creature. > > *I rejoiced in them all, because Wisdom is their leader, > though I had not known that she is their mother.*(Wisdom7:12) > > > In eternity the birth of Spirit of Wisdom, the Mother of all the Living in the order of grace is the First Act of God before He created everything, the Spirit of the Mother of all the living the source of breath must be created first. All creation are connected to Wisdom and human formed had the source of life thru the breath of God which is the Wisdom in Proverbs8:22. In closing, *Jesus the begotten son of God the Logos* existed in eternity at the ***"bosom of the Abba Father"*** while the *"Spirit of Wisdom"* birthed or created by God was ***"beside Him***" meaning Wisdom is external. In eternity, the Most Holy Trinity existed plus the Spirit of Created Wisdom that encompasses the Salvation of Mankind the Divine Plan of God from alpha to omega.
195,146
Consider the ring $\mathbb Z\_4[x]$. Clearly the elements of the form $2f(x)$ are zero divisors. > > **1**. Is it true that they are *all* the zero divisors? I mean is it true that if $p(x)$ is a zero divisor then it is of the form > $$ > 2f(x) > $$ > for some $f(x) \in \mathbb Z\_4[x]$? In other words, is the set of zero-divisors exactly the ideal $(2)$? > > > I believe it is true, but I do not know how to prove it. Secondly, the elements $1+g(x)$, with $g(x)$ zero divisors, are clearly units: $(1+g(x))^2=1$. > > **2**. Is it true that they are *all* the units? I mean is it true that if $p(x)\in \mathbb Z\_4[x]$ is a unit then it is of the form > $$ > 1+g(x) > $$ > for some zero divisor $g(x)$? > > >
2012/09/13
[ "https://math.stackexchange.com/questions/195146", "https://math.stackexchange.com", "https://math.stackexchange.com/users/28746/" ]
Both results follow from general characterizations of zero-divisors and units in polynomial rings. It's more insightful (and just as simple) to give the general proofs, then specialize them as below. $\rm(1)\ $ [McCoy's theorem](https://math.stackexchange.com/a/83171/242) states: $ $ if $\rm\:f\in R[x]\:$ is a zero-divisor then $\rm\:r\,f = 0\:$ for some nonzero $\rm\:r\in R.\:$ Thus $\rm\,f\,$ zero-divisor in $\rm\:\Bbb Z\_4[x]\:\Rightarrow\:c\,f = 0\:$ for $\rm\:0\ne c\in \Bbb Z\_4,\,$ so in $\rm\:\Bbb Z[x],\,\ 4\:|\:cf,\ 4\nmid c,f\:\Rightarrow\:2\:|\:c,f.\ $ $\rm(2)\ $ It is [very easy to prove](https://math.stackexchange.com/a/83886/242) that $\rm\:f(x)\in R[x]\:$ is a unit iff $\rm\:f(0)\:$ is a unit and all other nonzero coefficients are nilpotent. But the only nilpotent in $\rm\,\Bbb Z\_4\,$ is $\,2$.
You're right on both accounts. **1.** First notice that if $p(x)$ has zero constant coefficient, say $p(x)=x^mq(x)$, then $p(x)$ is a zero divisor if and only if $q(x)$ is. So suppose $p(x) = \sum\_0^n a\_ix^i \in \mathbb{Z}\_4[x]$ has an odd coefficient and a nonzero constant coefficient, and let $k \le n$ be least such that $a\_k$ is odd. Then all the $a\_j$ for $j < k$ are even. If $k=0$ then clearly $p$ is not a zero divisor (why?) so we must have $a\_0=2$. If $q(x) = \sum\_0^m b\_ix^i \in \mathbb{Z}\_4[x]$ is another polynomial (with nonzero constant coefficient, for the same reason as above), then the coefficient of $x^k$ in $p(x)q(x)$ is $$\sum\_{i+j=k} a\_ib\_j$$ If $p(x)q(x)=0$ then we must have $b\_0=2$. But then $$\sum\_{i+j=k} a\_ib\_j = 2a\_k + \cdots \equiv 2 + \cdots \pmod 4$$ and so $b\_{\ell}$ is odd for some $\ell<k$; otherwise the other terms would all disappear and we'd be left with $2$. But $q$ is a zero divisor with nonzero constant coefficient, and so interchanging the roles of $p$ and $q$ in the above, we see that $a\_i$ is odd for some $i<\ell<k$, contradicting minimality of $k$. **2.** Certainly if $p(x)q(x)=1$ then their constant coefficients are either both $1$ or both $3$. So $p(x)=1+g(x)$ and $q(x)=1+h(x)$ for some $g,h$ with equal even constant coefficients; and then $g(x)+h(x)+g(x)h(x)=0$. Let $g(x)=\sum\_0^n c\_ix^i$ and $h(x)=\sum\_0^m d\_ix^i$, and let $k$ be least such that at least one of $c\_k$ or $d\_k$ is odd. [We must have $k \ge 1$.] Then $$c\_k + d\_k + \sum\_{i+j=k} c\_id\_j = 0$$ We must therefore have $c\_k$ and $d\_k$ both odd. But $c\_0=d\_0$ is even, and so $$c\_k + d\_k + \sum\_{i+j=k} c\_id\_j = c\_k+d\_k+c\_0d\_k+c\_kd\_0 = (1+c\_0)(c\_k+d\_k) \equiv 2 \pmod 4$$ since the rest of the terms in the sum are zero. This is a contradiction, so $g$ and $h$ must both be divisible by $2$, and so indeed $p(x)=1+g(x)$ where $g$ is a zero divisor.
195,146
Consider the ring $\mathbb Z\_4[x]$. Clearly the elements of the form $2f(x)$ are zero divisors. > > **1**. Is it true that they are *all* the zero divisors? I mean is it true that if $p(x)$ is a zero divisor then it is of the form > $$ > 2f(x) > $$ > for some $f(x) \in \mathbb Z\_4[x]$? In other words, is the set of zero-divisors exactly the ideal $(2)$? > > > I believe it is true, but I do not know how to prove it. Secondly, the elements $1+g(x)$, with $g(x)$ zero divisors, are clearly units: $(1+g(x))^2=1$. > > **2**. Is it true that they are *all* the units? I mean is it true that if $p(x)\in \mathbb Z\_4[x]$ is a unit then it is of the form > $$ > 1+g(x) > $$ > for some zero divisor $g(x)$? > > >
2012/09/13
[ "https://math.stackexchange.com/questions/195146", "https://math.stackexchange.com", "https://math.stackexchange.com/users/28746/" ]
You're right on both accounts. **1.** First notice that if $p(x)$ has zero constant coefficient, say $p(x)=x^mq(x)$, then $p(x)$ is a zero divisor if and only if $q(x)$ is. So suppose $p(x) = \sum\_0^n a\_ix^i \in \mathbb{Z}\_4[x]$ has an odd coefficient and a nonzero constant coefficient, and let $k \le n$ be least such that $a\_k$ is odd. Then all the $a\_j$ for $j < k$ are even. If $k=0$ then clearly $p$ is not a zero divisor (why?) so we must have $a\_0=2$. If $q(x) = \sum\_0^m b\_ix^i \in \mathbb{Z}\_4[x]$ is another polynomial (with nonzero constant coefficient, for the same reason as above), then the coefficient of $x^k$ in $p(x)q(x)$ is $$\sum\_{i+j=k} a\_ib\_j$$ If $p(x)q(x)=0$ then we must have $b\_0=2$. But then $$\sum\_{i+j=k} a\_ib\_j = 2a\_k + \cdots \equiv 2 + \cdots \pmod 4$$ and so $b\_{\ell}$ is odd for some $\ell<k$; otherwise the other terms would all disappear and we'd be left with $2$. But $q$ is a zero divisor with nonzero constant coefficient, and so interchanging the roles of $p$ and $q$ in the above, we see that $a\_i$ is odd for some $i<\ell<k$, contradicting minimality of $k$. **2.** Certainly if $p(x)q(x)=1$ then their constant coefficients are either both $1$ or both $3$. So $p(x)=1+g(x)$ and $q(x)=1+h(x)$ for some $g,h$ with equal even constant coefficients; and then $g(x)+h(x)+g(x)h(x)=0$. Let $g(x)=\sum\_0^n c\_ix^i$ and $h(x)=\sum\_0^m d\_ix^i$, and let $k$ be least such that at least one of $c\_k$ or $d\_k$ is odd. [We must have $k \ge 1$.] Then $$c\_k + d\_k + \sum\_{i+j=k} c\_id\_j = 0$$ We must therefore have $c\_k$ and $d\_k$ both odd. But $c\_0=d\_0$ is even, and so $$c\_k + d\_k + \sum\_{i+j=k} c\_id\_j = c\_k+d\_k+c\_0d\_k+c\_kd\_0 = (1+c\_0)(c\_k+d\_k) \equiv 2 \pmod 4$$ since the rest of the terms in the sum are zero. This is a contradiction, so $g$ and $h$ must both be divisible by $2$, and so indeed $p(x)=1+g(x)$ where $g$ is a zero divisor.
Your first conjecture can be easily deduced by translating the problem to that of $\mathbb{Z}[x]$. The ring $\mathbb{Z}\_4[x]$ is (isomorphic to) the quotient ring $\mathbb{Z}[x] / (4)$, so we can write elements of $\mathbb{Z}\_4[x]$ as (equivalence classes of) integer polynomials. The condition to be a zero divisor of $\mathbb{Z}\_4[x]$ is > > u is a zero divisor if and only if there exists nonzero v such that $uv = 0$ > > > (I'm adopting the convention that 0 is a zero divisor) Lifting this condition to $\mathbb{Z}[x]$ gives > > The equivalence class of u is a zero divisor if and only if there exists $v \not\equiv 0 \pmod 4$ such that $uv \equiv 0 \pmod 4$. > > > Rephrasing in terms of divisibility, this means the prime factorization of $v$ may not have $2$, but the prime factorization of $uv$ must have at least 2 copies of two. Therefore, the prime factorization of $u$ must have a copy of $2$. Therefore, if the equivalence class of $u$ is a zero divisor, then $u = 2 g$ for some integer polynomial $g$.
195,146
Consider the ring $\mathbb Z\_4[x]$. Clearly the elements of the form $2f(x)$ are zero divisors. > > **1**. Is it true that they are *all* the zero divisors? I mean is it true that if $p(x)$ is a zero divisor then it is of the form > $$ > 2f(x) > $$ > for some $f(x) \in \mathbb Z\_4[x]$? In other words, is the set of zero-divisors exactly the ideal $(2)$? > > > I believe it is true, but I do not know how to prove it. Secondly, the elements $1+g(x)$, with $g(x)$ zero divisors, are clearly units: $(1+g(x))^2=1$. > > **2**. Is it true that they are *all* the units? I mean is it true that if $p(x)\in \mathbb Z\_4[x]$ is a unit then it is of the form > $$ > 1+g(x) > $$ > for some zero divisor $g(x)$? > > >
2012/09/13
[ "https://math.stackexchange.com/questions/195146", "https://math.stackexchange.com", "https://math.stackexchange.com/users/28746/" ]
Both results follow from general characterizations of zero-divisors and units in polynomial rings. It's more insightful (and just as simple) to give the general proofs, then specialize them as below. $\rm(1)\ $ [McCoy's theorem](https://math.stackexchange.com/a/83171/242) states: $ $ if $\rm\:f\in R[x]\:$ is a zero-divisor then $\rm\:r\,f = 0\:$ for some nonzero $\rm\:r\in R.\:$ Thus $\rm\,f\,$ zero-divisor in $\rm\:\Bbb Z\_4[x]\:\Rightarrow\:c\,f = 0\:$ for $\rm\:0\ne c\in \Bbb Z\_4,\,$ so in $\rm\:\Bbb Z[x],\,\ 4\:|\:cf,\ 4\nmid c,f\:\Rightarrow\:2\:|\:c,f.\ $ $\rm(2)\ $ It is [very easy to prove](https://math.stackexchange.com/a/83886/242) that $\rm\:f(x)\in R[x]\:$ is a unit iff $\rm\:f(0)\:$ is a unit and all other nonzero coefficients are nilpotent. But the only nilpotent in $\rm\,\Bbb Z\_4\,$ is $\,2$.
Your first conjecture can be easily deduced by translating the problem to that of $\mathbb{Z}[x]$. The ring $\mathbb{Z}\_4[x]$ is (isomorphic to) the quotient ring $\mathbb{Z}[x] / (4)$, so we can write elements of $\mathbb{Z}\_4[x]$ as (equivalence classes of) integer polynomials. The condition to be a zero divisor of $\mathbb{Z}\_4[x]$ is > > u is a zero divisor if and only if there exists nonzero v such that $uv = 0$ > > > (I'm adopting the convention that 0 is a zero divisor) Lifting this condition to $\mathbb{Z}[x]$ gives > > The equivalence class of u is a zero divisor if and only if there exists $v \not\equiv 0 \pmod 4$ such that $uv \equiv 0 \pmod 4$. > > > Rephrasing in terms of divisibility, this means the prime factorization of $v$ may not have $2$, but the prime factorization of $uv$ must have at least 2 copies of two. Therefore, the prime factorization of $u$ must have a copy of $2$. Therefore, if the equivalence class of $u$ is a zero divisor, then $u = 2 g$ for some integer polynomial $g$.
158,936
I am designing a testing box that has as a specification supplying power safely to a product range that requires the following voltages: 24Vdc, 24Vac, 110Vac and 230Vac. I am intending to use transformers controlled by PLC's and a HMI screen. However, I am stuck with a health and safety issue. Currently one end of the output lead could have live wire when disconnected of the product and therefore hurt the operator. Is there any component that detects the continuity in a lead, and stops the current automatically when it has been detected that there is no path for the current to flow? Many thanks in advance, any help would be appreciated.
2015/03/09
[ "https://electronics.stackexchange.com/questions/158936", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/69541/" ]
A classic, if complex solution to this, is to superimpose a defined signal on the source test lead. It can be a simple low level square wave, or a digital pattern. Say somewhere around 20kHz to 40kHz. On the other other wire in your continuity tester, you look for the transmitted signal, and only energize the test voltage if it is present. You can do this with a 555 timer chip and a PLL like a 4046. Just make sure that the supervisory circuit is protected from the high voltage.
I once had to make a continuity test (part of a machine) that was fed to 120Vac PLC input card. It also had to be ungrounded, because the tested material was grounded. I have used 2 transformers, and the continuity test was done with a low voltage. I have actually used 120 to 3 V transformers. I am not sure what exactly is your requirement, maybe it can give you some idea. ![enter image description here](https://i.stack.imgur.com/r2Moz.png)
7,901,904
I'm trying to make a model of our universities Course management system (for the course). I stumbled upon a small limitation of **extends**, that is, it's impossible for a certain class to extend two classes. Here's the model: ``` Professor / Staff / \ Person Tutor \ / Student ``` So with that I get Staff and Student extending Person and Professor extending Staff. Now I have a small dilemma with class Tutor, who is basically a student (has studentID), but is in a sense University employee (holds Group lectures, responsible for a certain project, etc). Since I can't use two extends, what are other alternatives, and if possible could someone give a very simple example with **implements**? I've seen an example of interface of it, but I'm not exactly sure as how can I use it in my program, since Student is not an interface?
2011/10/26
[ "https://Stackoverflow.com/questions/7901904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/602385/" ]
Make `Student` and `Staff` interfaces implemented by `Tutor`. `Student` will declare a `getStudentId()` method, and `Staff` will declare `getLectures()`, `getProjects()` etc..
As others have noted, to do this in Java you need to define interfaces rather than superclasses. Java does not allow multiple extends. But there may be a better alternative than inheritance. In this, and almost any situation where I find myself tempted to have a subclass extend multiple superclasses, I try to find a way to model the situation with delegation rather than inheritance. Create a `Person` class that contains a set of `Role` objects where `Role` is an interface, and `Student` and `Staff` implement `Role`. Then a person can have multiple roles instead of "being" multiple types of person.
7,901,904
I'm trying to make a model of our universities Course management system (for the course). I stumbled upon a small limitation of **extends**, that is, it's impossible for a certain class to extend two classes. Here's the model: ``` Professor / Staff / \ Person Tutor \ / Student ``` So with that I get Staff and Student extending Person and Professor extending Staff. Now I have a small dilemma with class Tutor, who is basically a student (has studentID), but is in a sense University employee (holds Group lectures, responsible for a certain project, etc). Since I can't use two extends, what are other alternatives, and if possible could someone give a very simple example with **implements**? I've seen an example of interface of it, but I'm not exactly sure as how can I use it in my program, since Student is not an interface?
2011/10/26
[ "https://Stackoverflow.com/questions/7901904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/602385/" ]
Don't use inheritance, use composition: everybody is a Person, but has one or more roles: Student, Tutor, Professor, Staff. Or optionally make a division between Staff and Student and allow them to have the roles. The roles then dictate what they can or cannot do.
Make `Student` and `Staff` interfaces implemented by `Tutor`. `Student` will declare a `getStudentId()` method, and `Staff` will declare `getLectures()`, `getProjects()` etc..
7,901,904
I'm trying to make a model of our universities Course management system (for the course). I stumbled upon a small limitation of **extends**, that is, it's impossible for a certain class to extend two classes. Here's the model: ``` Professor / Staff / \ Person Tutor \ / Student ``` So with that I get Staff and Student extending Person and Professor extending Staff. Now I have a small dilemma with class Tutor, who is basically a student (has studentID), but is in a sense University employee (holds Group lectures, responsible for a certain project, etc). Since I can't use two extends, what are other alternatives, and if possible could someone give a very simple example with **implements**? I've seen an example of interface of it, but I'm not exactly sure as how can I use it in my program, since Student is not an interface?
2011/10/26
[ "https://Stackoverflow.com/questions/7901904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/602385/" ]
Make Person, Staff, and Student interfaces. If you need common functionality, use encapsulation.
As others have noted, to do this in Java you need to define interfaces rather than superclasses. Java does not allow multiple extends. But there may be a better alternative than inheritance. In this, and almost any situation where I find myself tempted to have a subclass extend multiple superclasses, I try to find a way to model the situation with delegation rather than inheritance. Create a `Person` class that contains a set of `Role` objects where `Role` is an interface, and `Student` and `Staff` implement `Role`. Then a person can have multiple roles instead of "being" multiple types of person.
7,901,904
I'm trying to make a model of our universities Course management system (for the course). I stumbled upon a small limitation of **extends**, that is, it's impossible for a certain class to extend two classes. Here's the model: ``` Professor / Staff / \ Person Tutor \ / Student ``` So with that I get Staff and Student extending Person and Professor extending Staff. Now I have a small dilemma with class Tutor, who is basically a student (has studentID), but is in a sense University employee (holds Group lectures, responsible for a certain project, etc). Since I can't use two extends, what are other alternatives, and if possible could someone give a very simple example with **implements**? I've seen an example of interface of it, but I'm not exactly sure as how can I use it in my program, since Student is not an interface?
2011/10/26
[ "https://Stackoverflow.com/questions/7901904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/602385/" ]
Don't use inheritance, use composition: everybody is a Person, but has one or more roles: Student, Tutor, Professor, Staff. Or optionally make a division between Staff and Student and allow them to have the roles. The roles then dictate what they can or cannot do.
Make Person, Staff, and Student interfaces. If you need common functionality, use encapsulation.
7,901,904
I'm trying to make a model of our universities Course management system (for the course). I stumbled upon a small limitation of **extends**, that is, it's impossible for a certain class to extend two classes. Here's the model: ``` Professor / Staff / \ Person Tutor \ / Student ``` So with that I get Staff and Student extending Person and Professor extending Staff. Now I have a small dilemma with class Tutor, who is basically a student (has studentID), but is in a sense University employee (holds Group lectures, responsible for a certain project, etc). Since I can't use two extends, what are other alternatives, and if possible could someone give a very simple example with **implements**? I've seen an example of interface of it, but I'm not exactly sure as how can I use it in my program, since Student is not an interface?
2011/10/26
[ "https://Stackoverflow.com/questions/7901904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/602385/" ]
You can do something like this. ``` interface Person { ... } interface Staff extends Person { ... } interface Student extends Person { ... } class Tutor implements Staff, Student { ... } class Professor implements Staff { ... } ``` Unfortunately, you can't put logic (i.e., fields or non-abstract methods) in both `Staff` and `Student` because they would both need to be classes, and a Java class cannot extend two classes. You could make `Student` *or* `Staff` (not both) an abstract class, allowing you to put logic in it. It would be kind of inelegant, though, since there's no conceptual reason why one should be an abstract class while one should be an interface. Ideally they should both be abstract classes, but for that you'd need to switch to a language with MI. ``` interface Person { ... } interface Staff extends Person { ... } abstract class Student implements Person { long studentID; ... } class Tutor extends Student implements Staff { ... } class Professor implements Staff { ... } ```
As others have noted, to do this in Java you need to define interfaces rather than superclasses. Java does not allow multiple extends. But there may be a better alternative than inheritance. In this, and almost any situation where I find myself tempted to have a subclass extend multiple superclasses, I try to find a way to model the situation with delegation rather than inheritance. Create a `Person` class that contains a set of `Role` objects where `Role` is an interface, and `Student` and `Staff` implement `Role`. Then a person can have multiple roles instead of "being" multiple types of person.
7,901,904
I'm trying to make a model of our universities Course management system (for the course). I stumbled upon a small limitation of **extends**, that is, it's impossible for a certain class to extend two classes. Here's the model: ``` Professor / Staff / \ Person Tutor \ / Student ``` So with that I get Staff and Student extending Person and Professor extending Staff. Now I have a small dilemma with class Tutor, who is basically a student (has studentID), but is in a sense University employee (holds Group lectures, responsible for a certain project, etc). Since I can't use two extends, what are other alternatives, and if possible could someone give a very simple example with **implements**? I've seen an example of interface of it, but I'm not exactly sure as how can I use it in my program, since Student is not an interface?
2011/10/26
[ "https://Stackoverflow.com/questions/7901904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/602385/" ]
Don't use inheritance, use composition: everybody is a Person, but has one or more roles: Student, Tutor, Professor, Staff. Or optionally make a division between Staff and Student and allow them to have the roles. The roles then dictate what they can or cannot do.
You can do something like this. ``` interface Person { ... } interface Staff extends Person { ... } interface Student extends Person { ... } class Tutor implements Staff, Student { ... } class Professor implements Staff { ... } ``` Unfortunately, you can't put logic (i.e., fields or non-abstract methods) in both `Staff` and `Student` because they would both need to be classes, and a Java class cannot extend two classes. You could make `Student` *or* `Staff` (not both) an abstract class, allowing you to put logic in it. It would be kind of inelegant, though, since there's no conceptual reason why one should be an abstract class while one should be an interface. Ideally they should both be abstract classes, but for that you'd need to switch to a language with MI. ``` interface Person { ... } interface Staff extends Person { ... } abstract class Student implements Person { long studentID; ... } class Tutor extends Student implements Staff { ... } class Professor implements Staff { ... } ```
7,901,904
I'm trying to make a model of our universities Course management system (for the course). I stumbled upon a small limitation of **extends**, that is, it's impossible for a certain class to extend two classes. Here's the model: ``` Professor / Staff / \ Person Tutor \ / Student ``` So with that I get Staff and Student extending Person and Professor extending Staff. Now I have a small dilemma with class Tutor, who is basically a student (has studentID), but is in a sense University employee (holds Group lectures, responsible for a certain project, etc). Since I can't use two extends, what are other alternatives, and if possible could someone give a very simple example with **implements**? I've seen an example of interface of it, but I'm not exactly sure as how can I use it in my program, since Student is not an interface?
2011/10/26
[ "https://Stackoverflow.com/questions/7901904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/602385/" ]
Don't use inheritance, use composition: everybody is a Person, but has one or more roles: Student, Tutor, Professor, Staff. Or optionally make a division between Staff and Student and allow them to have the roles. The roles then dictate what they can or cannot do.
As others have noted, to do this in Java you need to define interfaces rather than superclasses. Java does not allow multiple extends. But there may be a better alternative than inheritance. In this, and almost any situation where I find myself tempted to have a subclass extend multiple superclasses, I try to find a way to model the situation with delegation rather than inheritance. Create a `Person` class that contains a set of `Role` objects where `Role` is an interface, and `Student` and `Staff` implement `Role`. Then a person can have multiple roles instead of "being" multiple types of person.
235,490
I am watching a movie in which two people fight with two zombies. One of them says "Do you want to switch?" and other says "How would that benefit me?" In the second sentence can I replace "would" with "will"?
2020/01/18
[ "https://ell.stackexchange.com/questions/235490", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/106867/" ]
Yes, however the word "would" is a "lets just say this happened" or "might" but "not guaranteed" situation. When you change it to say "will", it changes the story to mean something that is going to happen .
You can do it. But, the meaning of the sentence, which paraphrase looks like that 'How do you imagine my benefit from switching ? ' will change to the meaning of 'What is your sure knowledge about my benefit from switching?'
41,455
So, I've read in several books -- particularly [the novelization of Episode III](https://starwars.fandom.com/wiki/Star_Wars_Episode_III:_Revenge_of_the_Sith_%28novel%29) -- that Mace Windu created the Vaapad form of lightsaber combat. However, I recently read the first two Darth Bane novels, and a mention is made to Vaapad in the first book as well. If that's the case, clearly Mace Windu did not come up with it. So, which explanation of the origin is correct? **UPDATE**. From [the first Darth Bane novel](https://starwars.fandom.com/wiki/Darth_Bane:_Path_of_Destruction)... > > “At one moment Sirak seemed to be using the jabs and thrusts of Vaapad, the most aggressive and direct of the seven traditional forms. But in the middle of a sequence he would suddenly shift to the power attacks of Djem So, generating such force that even a blocked strike caused Bane to stagger back” > > >
2013/10/10
[ "https://scifi.stackexchange.com/questions/41455", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/9154/" ]
**TL;DR** Both answers are actually correct, as the differences stem from a technicality. The relevant quotes are: > > Vaapad is as aggressive and powerful as its namesake, but its power comes at great risk: immersion in Vaapad opens the gates that restrain one's inner darkness. To use Vaapad, a Jedi must allow himself to *enjoy* the fight he must give himself over to the thrill of battle. The rush of *winning*. Vaapad is a path that leads through the penumbra of the dark side. > > > Mace Windu created this style, and he was its only living master. > > > [*Revenge of the Sith* novelization](https://books.google.com/books?id=HiWsyea8Ay4C&printsec=frontcover#v=onepage&q&f=false), page 329 Wookieepedia has this quote listed: > > I created Vaapad to answer my weakness: it channels my own darkness into a weapon of the light. *(Mace Windu to Obi-Wan Kenobi, Revenge of the Sith novelization)* > > > But according to a google books search, it does not exist in the novel. From the book *[Shatterpoint](https://starwars.fandom.com/wiki/Shatterpoint_%28novel%29)*, said by Yoda: > > Six there were for generations of Jedi. The seventh, is not well-known. Powerful form it is. Deadliest of all. But dangerous it is, for its master as well as its opponent. Few have studied. One student alone, to mastery has risen. > > > It should be noted that there were *technically two variations* of [Form VII](https://starwars.fandom.com/wiki/Form_VII:_Juyo_/_Vaapad) - Juyo and Vaapad. Juyo was the older version, taught sparingly even then among the Jedi and then falling out of favor. Vaapad was "re-discovered" by Windu, along with [Sora Bulq](https://starwars.fandom.com/wiki/Sora_Bulq). The Wookieepedia article on it has this to say (sourced): > > the mastery required to learn Form VII was such that only a select few would be allowed to utilize it; he forbade its study to all others. At least two users of its Vaapad variant during Drallig's tenure described the form as dangerous due to its focus on physical combat and intensity. For his part, Drallig refused to allow Anakin Skywalker to study Juyo, while Obi-Wan Kenobi was likewise forbidden to learn Vaapad by Qui-Gon Jinn. > > > ... > > > Jaric Kaedan, a Jedi Master who fought in the Great Galactic War, was a master of the form—which was known as Juyo-Kos by that time—and he was considered a living weapon guided by the will of the Force itself. Another Great Galactic War combatant, the Sith Lord Scourge also employed Juyo...Another Sith Lord of that era, Darth Bane, was proficient in the use of Juyo. > > > As to why the term "Vaapad" appears in *Darth Bane*, there is this: > > The Sith apprentice Sirak in Darth Bane: Path of Destruction was stated to be a Vaapad practitioner, long before the style was created by Mace Windu. At a book signing in Huntington Beach, California, author Drew Karpyshyn said, "I meant Juyo, but it was a late night when I wrote that and didn't catch it until it was too late. That's one mistake I wish to God I could change. So when you read it and see 'Vaapad', just pretend it says 'Juyo.'" Star Wars Insider 92 later explained it by stating that "juyo" was another term for the vaapad creature the form was named after. > > > [This section](https://starwars.fandom.com/wiki/Form_VII:_Juyo_/_Vaapad#Practitioners) of the article has more information on the differences between Juyo and Vaapad.
It depends on which canon you wish to follow. As per [Wookieepedia](https://starwars.fandom.com/wiki/Canon): > > **G-canon is George Lucas Canon**; the six Episodes and any statements by George Lucas (including unpublished production notes from him or his production department that are never seen by the public). Elements originating with Lucas in the movie novelizations, reference books, and other sources are also G-canon, though anything created by the authors of those sources is C-canon. When the matter of changes between movie versions arises, the most recently released editions are deemed superior to older ones, as they correct mistakes, improve consistency between the two trilogies, and express Lucas's current vision of the Star Wars universe most closely. The deleted scenes included on the DVDs are also considered G-canon (when they're not in conflict with the movie). > > > **T-canon, or Television Canon**, refers to the canon level comprising the feature film Star Wars: The Clone Wars and the two television shows Star Wars: The Clone Wars and the Star Wars live-action TV series. It was devised recently in order to define a status above the C-Level canon, as confirmed by Chee. > > > **C-canon is Continuity Canon**, consisting of all recent works (and many older works) released under the name of Star Wars: books, comics, games, cartoons, non-theatrical films, and more. Games are a special case, as generally only the stories are C-canon, while things like stats and gameplay may not be; they also offer non-canonical options to the player, such as choosing female gender for a canonically male character. C-canon elements have been known to appear in the movies, thus making them G-canon; examples include the name "Coruscant," swoop bikes, Quinlan Vos, Aayla Secura, YT-2400 freighters and Action VI transports. > > > **S-canon is Secondary Canon**; the materials are available to be used or ignored as needed by current authors. This includes mostly older works, such as much of the Marvel Star Wars comics, that predate a consistent effort to maintain continuity; it also contains certain elements of a few otherwise N-canon stories, and other things that "may not fit just right." Many formerly S-canon elements have been elevated to C-canon through their inclusion in more recent works by continuity-minded authors, while many other older works (such as The Han Solo Adventures) were accounted for in continuity from the start despite their age, and thus were always C-canon. > > > **N is Non-Canon**. What-if stories (such as stories published under the Infinities label) and anything else directly and irreconcilably contradicted by higher canon ends up here. N is the only level that is not considered canon by Lucasfilm. Information cut from canon, deleted scenes, or from canceled Star Wars works falls into this category as well, unless another canonical work references it and it is declared canon. > > > **D is Detours Canon**, used for material hailing from Star Wars Detours. > > > Most of the novelization of episode three would fall in to **G-Canon**, but as Vaapad is not mentioned in the final films, that portion would fall into **C Canon**. The Darth Bane novels would fall under the **C Canon** by default. Since both portions of the books in question would fall under **C Canon**, neither is necessarily "more correct" than the other. Based on Wookieepedia's [entry on Vaapad](https://starwars.fandom.com/wiki/Form_VII:_Juyo_/_Vaapad), Darth Bane is a practitioner of Juyo - an early form of Vaapad. There are no referenced citations of Vaapad in the Darth Bane books in the article. If this is the case, there is no conflict in who created it.
41,455
So, I've read in several books -- particularly [the novelization of Episode III](https://starwars.fandom.com/wiki/Star_Wars_Episode_III:_Revenge_of_the_Sith_%28novel%29) -- that Mace Windu created the Vaapad form of lightsaber combat. However, I recently read the first two Darth Bane novels, and a mention is made to Vaapad in the first book as well. If that's the case, clearly Mace Windu did not come up with it. So, which explanation of the origin is correct? **UPDATE**. From [the first Darth Bane novel](https://starwars.fandom.com/wiki/Darth_Bane:_Path_of_Destruction)... > > “At one moment Sirak seemed to be using the jabs and thrusts of Vaapad, the most aggressive and direct of the seven traditional forms. But in the middle of a sequence he would suddenly shift to the power attacks of Djem So, generating such force that even a blocked strike caused Bane to stagger back” > > >
2013/10/10
[ "https://scifi.stackexchange.com/questions/41455", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/9154/" ]
The book [*The Jedi Path*](https://starwars.fandom.com/wiki/The_Jedi_Path:_A_Manual_for_Students_of_the_Force_%28real-life_book%29) has a "handwritten note" from Obi-Wan Kenobi on the page about Form VII - Juyo: > > Master Windu has developed a variant of Form VII called Vaapad. > > > This suggests that while the original Form VII was in fact called Juyo, Mace Windu developed Vaapad himself.
It depends on which canon you wish to follow. As per [Wookieepedia](https://starwars.fandom.com/wiki/Canon): > > **G-canon is George Lucas Canon**; the six Episodes and any statements by George Lucas (including unpublished production notes from him or his production department that are never seen by the public). Elements originating with Lucas in the movie novelizations, reference books, and other sources are also G-canon, though anything created by the authors of those sources is C-canon. When the matter of changes between movie versions arises, the most recently released editions are deemed superior to older ones, as they correct mistakes, improve consistency between the two trilogies, and express Lucas's current vision of the Star Wars universe most closely. The deleted scenes included on the DVDs are also considered G-canon (when they're not in conflict with the movie). > > > **T-canon, or Television Canon**, refers to the canon level comprising the feature film Star Wars: The Clone Wars and the two television shows Star Wars: The Clone Wars and the Star Wars live-action TV series. It was devised recently in order to define a status above the C-Level canon, as confirmed by Chee. > > > **C-canon is Continuity Canon**, consisting of all recent works (and many older works) released under the name of Star Wars: books, comics, games, cartoons, non-theatrical films, and more. Games are a special case, as generally only the stories are C-canon, while things like stats and gameplay may not be; they also offer non-canonical options to the player, such as choosing female gender for a canonically male character. C-canon elements have been known to appear in the movies, thus making them G-canon; examples include the name "Coruscant," swoop bikes, Quinlan Vos, Aayla Secura, YT-2400 freighters and Action VI transports. > > > **S-canon is Secondary Canon**; the materials are available to be used or ignored as needed by current authors. This includes mostly older works, such as much of the Marvel Star Wars comics, that predate a consistent effort to maintain continuity; it also contains certain elements of a few otherwise N-canon stories, and other things that "may not fit just right." Many formerly S-canon elements have been elevated to C-canon through their inclusion in more recent works by continuity-minded authors, while many other older works (such as The Han Solo Adventures) were accounted for in continuity from the start despite their age, and thus were always C-canon. > > > **N is Non-Canon**. What-if stories (such as stories published under the Infinities label) and anything else directly and irreconcilably contradicted by higher canon ends up here. N is the only level that is not considered canon by Lucasfilm. Information cut from canon, deleted scenes, or from canceled Star Wars works falls into this category as well, unless another canonical work references it and it is declared canon. > > > **D is Detours Canon**, used for material hailing from Star Wars Detours. > > > Most of the novelization of episode three would fall in to **G-Canon**, but as Vaapad is not mentioned in the final films, that portion would fall into **C Canon**. The Darth Bane novels would fall under the **C Canon** by default. Since both portions of the books in question would fall under **C Canon**, neither is necessarily "more correct" than the other. Based on Wookieepedia's [entry on Vaapad](https://starwars.fandom.com/wiki/Form_VII:_Juyo_/_Vaapad), Darth Bane is a practitioner of Juyo - an early form of Vaapad. There are no referenced citations of Vaapad in the Darth Bane books in the article. If this is the case, there is no conflict in who created it.
41,455
So, I've read in several books -- particularly [the novelization of Episode III](https://starwars.fandom.com/wiki/Star_Wars_Episode_III:_Revenge_of_the_Sith_%28novel%29) -- that Mace Windu created the Vaapad form of lightsaber combat. However, I recently read the first two Darth Bane novels, and a mention is made to Vaapad in the first book as well. If that's the case, clearly Mace Windu did not come up with it. So, which explanation of the origin is correct? **UPDATE**. From [the first Darth Bane novel](https://starwars.fandom.com/wiki/Darth_Bane:_Path_of_Destruction)... > > “At one moment Sirak seemed to be using the jabs and thrusts of Vaapad, the most aggressive and direct of the seven traditional forms. But in the middle of a sequence he would suddenly shift to the power attacks of Djem So, generating such force that even a blocked strike caused Bane to stagger back” > > >
2013/10/10
[ "https://scifi.stackexchange.com/questions/41455", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/9154/" ]
**TL;DR** Both answers are actually correct, as the differences stem from a technicality. The relevant quotes are: > > Vaapad is as aggressive and powerful as its namesake, but its power comes at great risk: immersion in Vaapad opens the gates that restrain one's inner darkness. To use Vaapad, a Jedi must allow himself to *enjoy* the fight he must give himself over to the thrill of battle. The rush of *winning*. Vaapad is a path that leads through the penumbra of the dark side. > > > Mace Windu created this style, and he was its only living master. > > > [*Revenge of the Sith* novelization](https://books.google.com/books?id=HiWsyea8Ay4C&printsec=frontcover#v=onepage&q&f=false), page 329 Wookieepedia has this quote listed: > > I created Vaapad to answer my weakness: it channels my own darkness into a weapon of the light. *(Mace Windu to Obi-Wan Kenobi, Revenge of the Sith novelization)* > > > But according to a google books search, it does not exist in the novel. From the book *[Shatterpoint](https://starwars.fandom.com/wiki/Shatterpoint_%28novel%29)*, said by Yoda: > > Six there were for generations of Jedi. The seventh, is not well-known. Powerful form it is. Deadliest of all. But dangerous it is, for its master as well as its opponent. Few have studied. One student alone, to mastery has risen. > > > It should be noted that there were *technically two variations* of [Form VII](https://starwars.fandom.com/wiki/Form_VII:_Juyo_/_Vaapad) - Juyo and Vaapad. Juyo was the older version, taught sparingly even then among the Jedi and then falling out of favor. Vaapad was "re-discovered" by Windu, along with [Sora Bulq](https://starwars.fandom.com/wiki/Sora_Bulq). The Wookieepedia article on it has this to say (sourced): > > the mastery required to learn Form VII was such that only a select few would be allowed to utilize it; he forbade its study to all others. At least two users of its Vaapad variant during Drallig's tenure described the form as dangerous due to its focus on physical combat and intensity. For his part, Drallig refused to allow Anakin Skywalker to study Juyo, while Obi-Wan Kenobi was likewise forbidden to learn Vaapad by Qui-Gon Jinn. > > > ... > > > Jaric Kaedan, a Jedi Master who fought in the Great Galactic War, was a master of the form—which was known as Juyo-Kos by that time—and he was considered a living weapon guided by the will of the Force itself. Another Great Galactic War combatant, the Sith Lord Scourge also employed Juyo...Another Sith Lord of that era, Darth Bane, was proficient in the use of Juyo. > > > As to why the term "Vaapad" appears in *Darth Bane*, there is this: > > The Sith apprentice Sirak in Darth Bane: Path of Destruction was stated to be a Vaapad practitioner, long before the style was created by Mace Windu. At a book signing in Huntington Beach, California, author Drew Karpyshyn said, "I meant Juyo, but it was a late night when I wrote that and didn't catch it until it was too late. That's one mistake I wish to God I could change. So when you read it and see 'Vaapad', just pretend it says 'Juyo.'" Star Wars Insider 92 later explained it by stating that "juyo" was another term for the vaapad creature the form was named after. > > > [This section](https://starwars.fandom.com/wiki/Form_VII:_Juyo_/_Vaapad#Practitioners) of the article has more information on the differences between Juyo and Vaapad.
The book [*The Jedi Path*](https://starwars.fandom.com/wiki/The_Jedi_Path:_A_Manual_for_Students_of_the_Force_%28real-life_book%29) has a "handwritten note" from Obi-Wan Kenobi on the page about Form VII - Juyo: > > Master Windu has developed a variant of Form VII called Vaapad. > > > This suggests that while the original Form VII was in fact called Juyo, Mace Windu developed Vaapad himself.
25,273,784
I'm testing the observable pattern in javascript. My callbacks in the array never seem to execute. What is wrong with my syntax? ``` <script type="text/javascript"> var Book = function (value) { var onChanging = []; this.name = function () { for (var i = 0; i < onChanging.length; i++) { onChanging[i](); } return value; } this.addTest = function (fn) { onChanging.push(fn); } } var b = new Book(13); b.addTest(function () { console.log("executing"); return true; }); b.name = 15; </script> ```
2014/08/12
[ "https://Stackoverflow.com/questions/25273784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995864/" ]
Your function has to have arguments `a`, `b` and `c`, yet you're only passing it `a`. Thus the error. I don't understand why you're doing the `get` within the function, and I would instead do: ``` # whatever function fun = function(a, b, c) a + b + c # evaluate inside the data.table, *then* pass it to your function input1a[, lapply(1:2, function(i) fun(get(paste0('a', i)), get(paste0('b', i)), get(paste0('c', i)))), by = ID] ``` Should be obvious how to change to do `get` within the function if you so desire.
I would keep it simple: ``` fun <- function(a1, a2, b1, b2, c1, c2) { res1 = (a1 - constants$V2 * (b1 - c1)) res2 = (a2 - constants$V2 * (b2 - c2)) return(list(res1, res2)) } # no get or apply function input1a[, fun(a1, a2, b1, b2, c1, c2), by=ID] input1a ID V1 V2 1: 37 7344.6993 -12297.443 2: 45 -755.0824 -8537.864 3: 900 15988.7949 -31532.379 ```
30,388,035
I'm trying to update a single table in my record using the session.getCurrentSession().save(Bean); And I'm getting this error. I have cross checked my table and column names in my Database with the attributes in my POJO class. The hibernate.hbm2ddl.auto property is set to auto in my configuration file. Please help ``` SEVERE: Servlet.service() for servlet [spring] in context with path [/PhoneStore] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: Could not execute JDBC batch update; SQL [insert into MOBILEPHONES_TB (BATTERY, BRAND, COLOR, DISPLAY, MEMORY, MODEL_NAME, OS, PRIMARY_CAMERA, PROCESSOR, RESOLUTION, SCREEN_TYPE, SECONDARY_CAMERA, SIM_SIZE, SIM_TYPE, SIZE, MODEL_ID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update] with root cause java.sql.BatchUpdateException: ORA-01747: invalid user.table.column, table.column, or column specification at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10055) at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:213) at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297) at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:656) at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754) at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723) at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:375) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at $Proxy29.addPhone(Unknown Source) at com.wipro.phonestore.controller.AdminController.addPhone(AdminController.java:21) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:174) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560) at javax.servlet.http.HttpServlet.service(HttpServlet.java:647) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) ```
2015/05/22
[ "https://Stackoverflow.com/questions/30388035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3934294/" ]
I don't see how that statement could run in SQL\*Plus or SQL Developer. The name of one of your columns "**`SIZE`**" is an Oracle reserved word. It would need to be enclosed in double quotes, in order for it to be referenced in an INSERT statement. ``` INSERT INTO foo ("SIZE") VALUES ( ? ) ^ ^ ``` The Oracle error message ORA-1747 is pretty clear about what the problem is. Reference: <http://docs.oracle.com/cd/B19306_01/em.102/b40103/app_oracle_reserved_words.htm>
I changed my column name from Size to Phone\_Size and was able to insert the queries. Thanks. :)
31,326,710
I am using `clang-format` (version 3.5) with Emacs (version 24.5.2). Here is a simple piece of code formatted by `clang-format` in LLVM style: ``` int main() { std::cout << "> "; std::string word; while (std::cin >> word) { std::cout << std::accumulate(word.cbegin(), word.cend(), 0, [](int cur, char ch) { return cur + (ch - '0'); }) << std::endl << "> "; } return 0; } ``` Note how it aligned the body and the closing brace of the `lambda`. Is there any logic to this formatting or it's just a lack of support for `lambda`s? Are there configuration parameters of `clang-format` that I need to set to get better formatting?
2015/07/09
[ "https://Stackoverflow.com/questions/31326710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2725810/" ]
`std::accumulate(word.cbegin(), word.cend(), 0, [](int cur, char ch) { return cur + (ch - '0'); })` Here we have a long function call. To clean it up, we take the long argument, and we split it onto its own line: ``` std::accumulate(word.cbegin(), word.cend(), 0, [](int cur, char ch) { return cur + (ch - '0'); }) ``` when we do this, we indent the argument to line up with the `(`: ``` std::accumulate(word.cbegin(), word.cend(), 0, [](int cur, char ch) { return cur + (ch - '0'); }) ``` so far so good. Now we have an open `{`. Well, that means a new line ``` std::accumulate(word.cbegin(), word.cend(), 0, [](int cur, char ch) { return cur + (ch - '0'); }) ``` with an indent. Where is the base of the indent? Well, the start of the `std::accumulate`. Add 4 spaces: ``` std::accumulate(word.cbegin(), word.cend(), 0, [](int cur, char ch) { return cur + (ch - '0'); }) ``` then we hit the `}`. New line, backdent: ``` std::accumulate(word.cbegin(), word.cend(), 0, [](int cur, char ch) { return cur + (ch - '0'); }) ``` finally, embed this in the middle of a larger expression, and you get the mess you had above. The above is purely a reasonable story, and not based off expertise of `clang-format`. I cannot tell you how to make it better.
You might want [`AlignAfterOpenBracket: false`](http://clang.llvm.org/docs/ClangFormatStyleOptions.html#configurable-format-style-options) to bring that `[]` left. Aligning after open bracket causes too much wasted space in my opinion, it is a wonder that it is so popular. Use `ContinuationIndentWidth` to control how far indented the continuations should be. Lambdas still don't align perfectly, but at least your lambda opening isn't a mile to the right. I am not completely happy with clang-format's formatting of lambdas either.
14,891,385
I got a script that expects two args (filename and MD5hashval). I can extract just the hex output of MD5sum using md5sum test.sh | grep -om1 '^[0-9a-f]\*.' For some reason, the same cmd fails when invoked from a script. Whats the best way to check cmdline arguments passed to a Bash script? Here's what the code looks like: ``` #!/bin/bash while getopts ":f:s" opt; do case $opt in f) FILENAME=`echo $OPTARG | sed 's/[-a-zA-Z0-9]*=//'` echo ${FILENAME} ;; s) MD5SUM=`echo $OPTARG | grep -om1 '^[0-9a-f]*'` echo $MD5SUM ;; \?) echo "Invalid option: -$OPTARG" >&2 exit 1 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done ```
2013/02/15
[ "https://Stackoverflow.com/questions/14891385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999114/" ]
Since the `s` option requires an argument, you need to place a colon after it. It should be: ``` while getopts "f:s:" opt; do ... ``` From the `getopts` man page: > > if a character is followed by a colon, the option is expected > to have an argument, which should be separated from it by white space. > > >
My first action would be to place a debug line before your actual command: ``` echo "[$OPTARG]" MD5SUM=`echo $OPTARG | grep -om1 '^[0-9a-f]*'` ``` But it actually has to do with the fact that `s` is not followed by a colon in your `getopts` options string. You should use `f:s:` instead: > > ... optstring contains the option characters to be recognized; if a character is **followed** by a colon, the option is expected to have an argument, which should be separated from it by white space. > > > And, just as an aside, I think your error lines should be `-$opt` rather than `-$OPTARG`.
29,014,716
I'm trying to change the user's current culture via AJAX POST: ``` $.ajax({ type: 'POST', url: '/Account/SetDefaultCulture', data: data, dataType: 'JSON', success: function (result) { location.reload(true); } }); ``` With this controller method: ``` private readonly AspEntities db = new AspEntities(); [HttpPost] public JsonResult SetDefaultCulture(string userName, string culture) { if (!userName.IsNullOrEmpty()) { var user = (from a in _db.AspNetUsers where a.UserName == userName select a).FirstOrDefault(); if (user != null) { user.Culture = culture; db.SaveChanges(); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new CultureInfo(culture); return Json(new { culture, success = true }); } } return Json(new {culture, success = false}); } ``` If I step through while debugging, I can see the database record update right after `db.SaveChanges()` is called. The problem is the application/website doesn't update the user's Culture until AFTER I change some code in the Controller, and then build the project again. It's almost as if the Culture is being cached within the application or something. I must be missing something. Is this common? Has anyone encountered this? **EDIT** I am using a Utility method to check the current user's culture: ``` public static CultureInfo GetCulture() { var userId = HttpContext.Current.User.Identity.GetUserId(); var user = (from a in _db.AspNetUsers where a.Id == userId select a).FirstOrDefault(); var culture = "en-CA"; if (user != null) { if (!user.Culture.IsNullOrEmpty()) { culture = user.Culture; } } return new CultureInfo(culture); } ``` Within a Filter which runs on every page hit: ``` public class CheckCultureAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpContext ctx = HttpContext.Current; string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower().Trim(); string actionName = filterContext.ActionDescriptor.ActionName.ToLower().Trim(); //Set Culture var culture = (ctx.User != null) ? Utilities.GetCulture() : new CultureInfo("en-CA"); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = culture; ... } } ``` If I start the debugger and step through this filter, the `GetCulture()` method returns the non-updated value (which does not match the value that has been updated in the Database)
2015/03/12
[ "https://Stackoverflow.com/questions/29014716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2246329/" ]
Cant comment yet, but have you checked [this other stack overflow question](https://stackoverflow.com/questions/8226514/best-place-to-set-currentculture-for-multilingual-asp-net-mvc-web-applications) According to that link it seems that the action filter is already too late to set the culture for the request.
I think you first have to attach the user to your DbContext. ``` db.AspNetUsers.Attach(user); ``` Then call save changes. Every time I have run into issues updating my DB, this has been the cause. I do believe you have to refresh the page after this update too.
29,014,716
I'm trying to change the user's current culture via AJAX POST: ``` $.ajax({ type: 'POST', url: '/Account/SetDefaultCulture', data: data, dataType: 'JSON', success: function (result) { location.reload(true); } }); ``` With this controller method: ``` private readonly AspEntities db = new AspEntities(); [HttpPost] public JsonResult SetDefaultCulture(string userName, string culture) { if (!userName.IsNullOrEmpty()) { var user = (from a in _db.AspNetUsers where a.UserName == userName select a).FirstOrDefault(); if (user != null) { user.Culture = culture; db.SaveChanges(); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new CultureInfo(culture); return Json(new { culture, success = true }); } } return Json(new {culture, success = false}); } ``` If I step through while debugging, I can see the database record update right after `db.SaveChanges()` is called. The problem is the application/website doesn't update the user's Culture until AFTER I change some code in the Controller, and then build the project again. It's almost as if the Culture is being cached within the application or something. I must be missing something. Is this common? Has anyone encountered this? **EDIT** I am using a Utility method to check the current user's culture: ``` public static CultureInfo GetCulture() { var userId = HttpContext.Current.User.Identity.GetUserId(); var user = (from a in _db.AspNetUsers where a.Id == userId select a).FirstOrDefault(); var culture = "en-CA"; if (user != null) { if (!user.Culture.IsNullOrEmpty()) { culture = user.Culture; } } return new CultureInfo(culture); } ``` Within a Filter which runs on every page hit: ``` public class CheckCultureAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpContext ctx = HttpContext.Current; string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower().Trim(); string actionName = filterContext.ActionDescriptor.ActionName.ToLower().Trim(); //Set Culture var culture = (ctx.User != null) ? Utilities.GetCulture() : new CultureInfo("en-CA"); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = culture; ... } } ``` If I start the debugger and step through this filter, the `GetCulture()` method returns the non-updated value (which does not match the value that has been updated in the Database)
2015/03/12
[ "https://Stackoverflow.com/questions/29014716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2246329/" ]
Seems like EF is not tracking your changes. Try something like this, db.Entry(AspNetUsers).State = EntityState.Modified; before: db.SaveChanges(); Also you are quering \_db context while i can see that your context is private readonly AspEntities db = new AspEntities(); Which hints ur context is not set right? Don't know if I am correct but do check your context.
I think you first have to attach the user to your DbContext. ``` db.AspNetUsers.Attach(user); ``` Then call save changes. Every time I have run into issues updating my DB, this has been the cause. I do believe you have to refresh the page after this update too.
29,014,716
I'm trying to change the user's current culture via AJAX POST: ``` $.ajax({ type: 'POST', url: '/Account/SetDefaultCulture', data: data, dataType: 'JSON', success: function (result) { location.reload(true); } }); ``` With this controller method: ``` private readonly AspEntities db = new AspEntities(); [HttpPost] public JsonResult SetDefaultCulture(string userName, string culture) { if (!userName.IsNullOrEmpty()) { var user = (from a in _db.AspNetUsers where a.UserName == userName select a).FirstOrDefault(); if (user != null) { user.Culture = culture; db.SaveChanges(); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new CultureInfo(culture); return Json(new { culture, success = true }); } } return Json(new {culture, success = false}); } ``` If I step through while debugging, I can see the database record update right after `db.SaveChanges()` is called. The problem is the application/website doesn't update the user's Culture until AFTER I change some code in the Controller, and then build the project again. It's almost as if the Culture is being cached within the application or something. I must be missing something. Is this common? Has anyone encountered this? **EDIT** I am using a Utility method to check the current user's culture: ``` public static CultureInfo GetCulture() { var userId = HttpContext.Current.User.Identity.GetUserId(); var user = (from a in _db.AspNetUsers where a.Id == userId select a).FirstOrDefault(); var culture = "en-CA"; if (user != null) { if (!user.Culture.IsNullOrEmpty()) { culture = user.Culture; } } return new CultureInfo(culture); } ``` Within a Filter which runs on every page hit: ``` public class CheckCultureAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpContext ctx = HttpContext.Current; string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower().Trim(); string actionName = filterContext.ActionDescriptor.ActionName.ToLower().Trim(); //Set Culture var culture = (ctx.User != null) ? Utilities.GetCulture() : new CultureInfo("en-CA"); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = culture; ... } } ``` If I start the debugger and step through this filter, the `GetCulture()` method returns the non-updated value (which does not match the value that has been updated in the Database)
2015/03/12
[ "https://Stackoverflow.com/questions/29014716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2246329/" ]
Check to see if you are referencing data from an already instantiated database context (`AspEntities db`) in the controller that is supposed to produce the updates. The `readonly` modifier will prevent changes after declaration, unless you are always creating a new controller object.
I think you first have to attach the user to your DbContext. ``` db.AspNetUsers.Attach(user); ``` Then call save changes. Every time I have run into issues updating my DB, this has been the cause. I do believe you have to refresh the page after this update too.
29,014,716
I'm trying to change the user's current culture via AJAX POST: ``` $.ajax({ type: 'POST', url: '/Account/SetDefaultCulture', data: data, dataType: 'JSON', success: function (result) { location.reload(true); } }); ``` With this controller method: ``` private readonly AspEntities db = new AspEntities(); [HttpPost] public JsonResult SetDefaultCulture(string userName, string culture) { if (!userName.IsNullOrEmpty()) { var user = (from a in _db.AspNetUsers where a.UserName == userName select a).FirstOrDefault(); if (user != null) { user.Culture = culture; db.SaveChanges(); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new CultureInfo(culture); return Json(new { culture, success = true }); } } return Json(new {culture, success = false}); } ``` If I step through while debugging, I can see the database record update right after `db.SaveChanges()` is called. The problem is the application/website doesn't update the user's Culture until AFTER I change some code in the Controller, and then build the project again. It's almost as if the Culture is being cached within the application or something. I must be missing something. Is this common? Has anyone encountered this? **EDIT** I am using a Utility method to check the current user's culture: ``` public static CultureInfo GetCulture() { var userId = HttpContext.Current.User.Identity.GetUserId(); var user = (from a in _db.AspNetUsers where a.Id == userId select a).FirstOrDefault(); var culture = "en-CA"; if (user != null) { if (!user.Culture.IsNullOrEmpty()) { culture = user.Culture; } } return new CultureInfo(culture); } ``` Within a Filter which runs on every page hit: ``` public class CheckCultureAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpContext ctx = HttpContext.Current; string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower().Trim(); string actionName = filterContext.ActionDescriptor.ActionName.ToLower().Trim(); //Set Culture var culture = (ctx.User != null) ? Utilities.GetCulture() : new CultureInfo("en-CA"); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = culture; ... } } ``` If I start the debugger and step through this filter, the `GetCulture()` method returns the non-updated value (which does not match the value that has been updated in the Database)
2015/03/12
[ "https://Stackoverflow.com/questions/29014716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2246329/" ]
Seems like EF is not tracking your changes. Try something like this, db.Entry(AspNetUsers).State = EntityState.Modified; before: db.SaveChanges(); Also you are quering \_db context while i can see that your context is private readonly AspEntities db = new AspEntities(); Which hints ur context is not set right? Don't know if I am correct but do check your context.
Cant comment yet, but have you checked [this other stack overflow question](https://stackoverflow.com/questions/8226514/best-place-to-set-currentculture-for-multilingual-asp-net-mvc-web-applications) According to that link it seems that the action filter is already too late to set the culture for the request.
29,014,716
I'm trying to change the user's current culture via AJAX POST: ``` $.ajax({ type: 'POST', url: '/Account/SetDefaultCulture', data: data, dataType: 'JSON', success: function (result) { location.reload(true); } }); ``` With this controller method: ``` private readonly AspEntities db = new AspEntities(); [HttpPost] public JsonResult SetDefaultCulture(string userName, string culture) { if (!userName.IsNullOrEmpty()) { var user = (from a in _db.AspNetUsers where a.UserName == userName select a).FirstOrDefault(); if (user != null) { user.Culture = culture; db.SaveChanges(); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new CultureInfo(culture); return Json(new { culture, success = true }); } } return Json(new {culture, success = false}); } ``` If I step through while debugging, I can see the database record update right after `db.SaveChanges()` is called. The problem is the application/website doesn't update the user's Culture until AFTER I change some code in the Controller, and then build the project again. It's almost as if the Culture is being cached within the application or something. I must be missing something. Is this common? Has anyone encountered this? **EDIT** I am using a Utility method to check the current user's culture: ``` public static CultureInfo GetCulture() { var userId = HttpContext.Current.User.Identity.GetUserId(); var user = (from a in _db.AspNetUsers where a.Id == userId select a).FirstOrDefault(); var culture = "en-CA"; if (user != null) { if (!user.Culture.IsNullOrEmpty()) { culture = user.Culture; } } return new CultureInfo(culture); } ``` Within a Filter which runs on every page hit: ``` public class CheckCultureAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpContext ctx = HttpContext.Current; string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower().Trim(); string actionName = filterContext.ActionDescriptor.ActionName.ToLower().Trim(); //Set Culture var culture = (ctx.User != null) ? Utilities.GetCulture() : new CultureInfo("en-CA"); Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = culture; ... } } ``` If I start the debugger and step through this filter, the `GetCulture()` method returns the non-updated value (which does not match the value that has been updated in the Database)
2015/03/12
[ "https://Stackoverflow.com/questions/29014716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2246329/" ]
Seems like EF is not tracking your changes. Try something like this, db.Entry(AspNetUsers).State = EntityState.Modified; before: db.SaveChanges(); Also you are quering \_db context while i can see that your context is private readonly AspEntities db = new AspEntities(); Which hints ur context is not set right? Don't know if I am correct but do check your context.
Check to see if you are referencing data from an already instantiated database context (`AspEntities db`) in the controller that is supposed to produce the updates. The `readonly` modifier will prevent changes after declaration, unless you are always creating a new controller object.
19,671,348
I have a function that has a few possible return values. As a trivial example, let's imagine it took in a positive int and returned "small", "medium", or "large": ``` def size(x): if x < 10: return SMALL if x < 20: return MEDIUM return LARGE ``` I am wondering the best way to write & define the return values. I am wondering about using Python function attributes, as follows: ``` def size(x): if x < 10: return size.small if x < 20: return size.medium return size.large size.small = 1 size.medium = 2 size.large = 3 ``` Then my calling code would look like: ``` if size(n) == size.small: ... ``` This seems like a nice built-in "enum", possibly clearer/simpler than creating a module-level enum, or defining the 3 values as global constants like `SIZE_SMALL, SIZE_MEDIUM`, etc. But I don't think I've seen code like this before. Is this a good approach or are there pitfalls/drawbacks?
2013/10/29
[ "https://Stackoverflow.com/questions/19671348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38146/" ]
While you can, I wouldn't, especially now that Python has an [Enum type](http://www.python.org/dev/peps/pep-0435/) in 3.4 which has been [backported](https://pypi.python.org/pypi/enum34). Your example above might look like this as an `Enum`: ``` class Size(Enum): small = 1 medium = 2 large = 3 @classmethod def classify(cls, number): if number < 10: return cls.small elif number < 20: return cls.medium else: return cls.large ``` In use: ``` --> Size.classify(15) <Size.medium: 2> ```
[`namedtuple`](http://docs.python.org/2/library/collections.html#collections.namedtuple), perhaps? ``` >>> from collections import namedtuple >>> >>> SizeSpec = namedtuple('SizeSpec', ['small', 'medium', 'large']) >>> >>> size = SizeSpec(small=1, medium=2, large=3) >>> >>> size.small 1 >>> size.medium 2 >>> size.large 3 ```
11,007,509
I'm in a struts project. I wanted to create reusable custom tags. So heres the thing, for example i have this set of struts UI tags: ``` <s:form action="some.action" namespace="/somenamespace"> <s:textfield name="username" label="Username"/> <s:textfield name="pwd" label="Password" /> <s:submit value="login"/> </s:form> ``` Is it possible to come up with something like this to produce the same output instead of the code above: ``` <mycustomtag:login /> ```
2012/06/13
[ "https://Stackoverflow.com/questions/11007509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1297154/" ]
You are confusing two different styles of parameters in SQL queries. The ODBC syntax uses simple placeholder '?' character for each parameter, and the parameters are replaced in the same order that you add them to the parameters collection. For an `OdbcCommand`, the name you give the parameters is ignored, and only their sequence matters. For a `SqlCommand`, the parameter names are meaningful; when the command executes, it will be run through a SQL Stored procedure that takes a list of parameter names and values and substitutes them into the T-SQL query. In this case, the order you add parameters to your query isn't important, but you need to make sure the names are correct (including the "@" prefix.) The proper way to use a `SqlCommand` with parameters is as follows: ``` // The SQL Query: Note the use of named parameters of the form // @ParameterName1, @ParameterName2, etc. Dim sql As String = "INSERT INTO " & tableName & _ " (CHECKLIST_ID, TYPE, SHAPEDATA ) " & _ "VALUES " & _ " (@ChecklistId, @Type, @ShapeData )" // The Parameter List. Note that the Parameter name must exactly match // what you use in the query: Dim cmd As SqlCommand = New SqlCommand(sql, conn) cmd.Parameters.AddWithValue("@CheckListId", checklist_id) cmd.Parameters.AddWithValue("@Type", type) cmd.Parameters.AddWithValue("@ShapeData", shape.ShapeData) cmd.ExecuteNonQuery() ```
You should assign parameters like this and in your case you missed providing value for "CONECTION" parameter. Also as an additional note, you should always enclose connection objects in using blocks. See [this](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx) and look at the "Remarks" section. ``` command.CommandText = "INSERT INTO Table (Col1, Col2, Col3) VALUES _ (@Col1Val, @Col2Val, @Col3Val)" command.Parameters.AddWithValue("@Col1Val","1"); command.Parameters.AddWithValue("@Col2Val","2"); command.Parameters.AddWithValue("@Col3Val","3"); ```
11,007,509
I'm in a struts project. I wanted to create reusable custom tags. So heres the thing, for example i have this set of struts UI tags: ``` <s:form action="some.action" namespace="/somenamespace"> <s:textfield name="username" label="Username"/> <s:textfield name="pwd" label="Password" /> <s:submit value="login"/> </s:form> ``` Is it possible to come up with something like this to produce the same output instead of the code above: ``` <mycustomtag:login /> ```
2012/06/13
[ "https://Stackoverflow.com/questions/11007509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1297154/" ]
You should assign parameters like this and in your case you missed providing value for "CONECTION" parameter. Also as an additional note, you should always enclose connection objects in using blocks. See [this](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx) and look at the "Remarks" section. ``` command.CommandText = "INSERT INTO Table (Col1, Col2, Col3) VALUES _ (@Col1Val, @Col2Val, @Col3Val)" command.Parameters.AddWithValue("@Col1Val","1"); command.Parameters.AddWithValue("@Col2Val","2"); command.Parameters.AddWithValue("@Col3Val","3"); ```
Please make sure that `Dim cmd As SqlCommand = New SqlCommand(sql, conn)` uses `conn` with an open connection. Then verify your parameters type to be in accordance with the database table definition. Plus, If your using string type you may add an ' before and after any text inserted. To be sure, you can break on `cmd.ExecuteNonQuery()` and copy the value of the command associated and running it to any SQL manager tool. Finally, dispose your `cmd`. Otherwise check if this is helpful for your issue : <http://social.msdn.microsoft.com/Forums/en-US/sqlspatial/thread/9d75106a-b0d4-49cc-ac86-d41cba4ab797>
11,007,509
I'm in a struts project. I wanted to create reusable custom tags. So heres the thing, for example i have this set of struts UI tags: ``` <s:form action="some.action" namespace="/somenamespace"> <s:textfield name="username" label="Username"/> <s:textfield name="pwd" label="Password" /> <s:submit value="login"/> </s:form> ``` Is it possible to come up with something like this to produce the same output instead of the code above: ``` <mycustomtag:login /> ```
2012/06/13
[ "https://Stackoverflow.com/questions/11007509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1297154/" ]
You are confusing two different styles of parameters in SQL queries. The ODBC syntax uses simple placeholder '?' character for each parameter, and the parameters are replaced in the same order that you add them to the parameters collection. For an `OdbcCommand`, the name you give the parameters is ignored, and only their sequence matters. For a `SqlCommand`, the parameter names are meaningful; when the command executes, it will be run through a SQL Stored procedure that takes a list of parameter names and values and substitutes them into the T-SQL query. In this case, the order you add parameters to your query isn't important, but you need to make sure the names are correct (including the "@" prefix.) The proper way to use a `SqlCommand` with parameters is as follows: ``` // The SQL Query: Note the use of named parameters of the form // @ParameterName1, @ParameterName2, etc. Dim sql As String = "INSERT INTO " & tableName & _ " (CHECKLIST_ID, TYPE, SHAPEDATA ) " & _ "VALUES " & _ " (@ChecklistId, @Type, @ShapeData )" // The Parameter List. Note that the Parameter name must exactly match // what you use in the query: Dim cmd As SqlCommand = New SqlCommand(sql, conn) cmd.Parameters.AddWithValue("@CheckListId", checklist_id) cmd.Parameters.AddWithValue("@Type", type) cmd.Parameters.AddWithValue("@ShapeData", shape.ShapeData) cmd.ExecuteNonQuery() ```
Please make sure that `Dim cmd As SqlCommand = New SqlCommand(sql, conn)` uses `conn` with an open connection. Then verify your parameters type to be in accordance with the database table definition. Plus, If your using string type you may add an ' before and after any text inserted. To be sure, you can break on `cmd.ExecuteNonQuery()` and copy the value of the command associated and running it to any SQL manager tool. Finally, dispose your `cmd`. Otherwise check if this is helpful for your issue : <http://social.msdn.microsoft.com/Forums/en-US/sqlspatial/thread/9d75106a-b0d4-49cc-ac86-d41cba4ab797>
41,745,735
I want to: 1. pass a block to a method call, and then 2. pass that entire method call as the condition of a `while` loop, 3. even though I don't need to put any logic inside the loop itself. Specifically, I have an array that I'd like to `#reject!` certain elements from based on rather complicated logic. Subsequent calls to `#reject!` may remove elements that were not removed on a previous pass. When `#reject!` finally stops finding elements to reject, it will return `nil`. At this point, I would like the loop to stop and the program to proceed. I thought I could do the following: ```rb while array.reject! do |element| ... end end ``` I haven't actually tried it yet, but this construction throws vim's ruby syntax highlighter for a loop (*i.e.,* it thinks the first `do` is for the `while` statement, and thinks the second `end` is actually the end of the encapsulating method). I also tried rewriting this as an inline `while` modifier attached to a `begin...end` block, ```rb begin; end while array.reject! do |element| ... end ``` but it still screws up the highlighting in the same way. In any case, it feels like an abuse of the `while` loop. The only way I could think of to accomplish this is by assigning the method call as a proc: ```rb proc = Proc.new do array.reject! do |element| ... end end while proc.call do; end ``` which works but feels kludgy, especially with the trailing `do; end`. Is there any elegant way to accomplish this??
2017/01/19
[ "https://Stackoverflow.com/questions/41745735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4865822/" ]
It's not just vim, `while array.reject! do |element|` is invalid syntax: ``` $ ruby -c -e 'while array.reject! do |element| end' -e:1: syntax error, unexpected '|' while array.reject! do |element| end ^ ``` You could use `{ ... }` instead of `do ... end`: ``` while array.reject! { |element| # ... } end ``` or `loop` and `break`: ``` loop do break unless array.reject! do |element| # ... end end ``` a little more explicit: ``` loop do r = array.reject! do |element| # ... end break unless r end ```
You're right that the Ruby parser thinks that `do` belongs to `while`, and doesn't understand where the second `end` is coming from. It's a precedence problem. This code is just to show that it **can** be done. For how it **should** be done, see Stefan's [answer](https://stackoverflow.com/a/41746233/6419007) : ``` array = (1..1000).to_a while (array.reject! do |element| rand < 0.5 end) p array.size end ``` It outputs : ``` 473 238 113 47 30 18 8 1 0 ```
41,745,735
I want to: 1. pass a block to a method call, and then 2. pass that entire method call as the condition of a `while` loop, 3. even though I don't need to put any logic inside the loop itself. Specifically, I have an array that I'd like to `#reject!` certain elements from based on rather complicated logic. Subsequent calls to `#reject!` may remove elements that were not removed on a previous pass. When `#reject!` finally stops finding elements to reject, it will return `nil`. At this point, I would like the loop to stop and the program to proceed. I thought I could do the following: ```rb while array.reject! do |element| ... end end ``` I haven't actually tried it yet, but this construction throws vim's ruby syntax highlighter for a loop (*i.e.,* it thinks the first `do` is for the `while` statement, and thinks the second `end` is actually the end of the encapsulating method). I also tried rewriting this as an inline `while` modifier attached to a `begin...end` block, ```rb begin; end while array.reject! do |element| ... end ``` but it still screws up the highlighting in the same way. In any case, it feels like an abuse of the `while` loop. The only way I could think of to accomplish this is by assigning the method call as a proc: ```rb proc = Proc.new do array.reject! do |element| ... end end while proc.call do; end ``` which works but feels kludgy, especially with the trailing `do; end`. Is there any elegant way to accomplish this??
2017/01/19
[ "https://Stackoverflow.com/questions/41745735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4865822/" ]
It's not just vim, `while array.reject! do |element|` is invalid syntax: ``` $ ruby -c -e 'while array.reject! do |element| end' -e:1: syntax error, unexpected '|' while array.reject! do |element| end ^ ``` You could use `{ ... }` instead of `do ... end`: ``` while array.reject! { |element| # ... } end ``` or `loop` and `break`: ``` loop do break unless array.reject! do |element| # ... end end ``` a little more explicit: ``` loop do r = array.reject! do |element| # ... end break unless r end ```
My personal preference in situations where I need to call a method until the return value is what I want is: ``` :keep_going while my_method ``` Or more tersely I sometimes use: ``` :go while my_method ``` It's one line, and you can use the contents of the symbol to help document what's going on. With your block, I'd personally create a proc/lambda out of it and pass that to reject for clarity. ``` # Harder to follow, IMHO :keep_going while array.reject! do |...| more_code end # Easier to follow, IMHO simplify = ->(...){ ... } :keep_simplifying while array.reject!(&simplify) ```
41,745,735
I want to: 1. pass a block to a method call, and then 2. pass that entire method call as the condition of a `while` loop, 3. even though I don't need to put any logic inside the loop itself. Specifically, I have an array that I'd like to `#reject!` certain elements from based on rather complicated logic. Subsequent calls to `#reject!` may remove elements that were not removed on a previous pass. When `#reject!` finally stops finding elements to reject, it will return `nil`. At this point, I would like the loop to stop and the program to proceed. I thought I could do the following: ```rb while array.reject! do |element| ... end end ``` I haven't actually tried it yet, but this construction throws vim's ruby syntax highlighter for a loop (*i.e.,* it thinks the first `do` is for the `while` statement, and thinks the second `end` is actually the end of the encapsulating method). I also tried rewriting this as an inline `while` modifier attached to a `begin...end` block, ```rb begin; end while array.reject! do |element| ... end ``` but it still screws up the highlighting in the same way. In any case, it feels like an abuse of the `while` loop. The only way I could think of to accomplish this is by assigning the method call as a proc: ```rb proc = Proc.new do array.reject! do |element| ... end end while proc.call do; end ``` which works but feels kludgy, especially with the trailing `do; end`. Is there any elegant way to accomplish this??
2017/01/19
[ "https://Stackoverflow.com/questions/41745735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4865822/" ]
Ruby lets you move your condition to the end of the loop statement. This makes it easy to store a result inside of the loop and check it against the conditional: ``` begin any_rejected = arr.reject! { … } end while any_rejected ``` This would work the same as doing `end while arr.reject! { … }`, but it's much clearer here what's happening, especially with a complicated `reject!`.
You're right that the Ruby parser thinks that `do` belongs to `while`, and doesn't understand where the second `end` is coming from. It's a precedence problem. This code is just to show that it **can** be done. For how it **should** be done, see Stefan's [answer](https://stackoverflow.com/a/41746233/6419007) : ``` array = (1..1000).to_a while (array.reject! do |element| rand < 0.5 end) p array.size end ``` It outputs : ``` 473 238 113 47 30 18 8 1 0 ```
41,745,735
I want to: 1. pass a block to a method call, and then 2. pass that entire method call as the condition of a `while` loop, 3. even though I don't need to put any logic inside the loop itself. Specifically, I have an array that I'd like to `#reject!` certain elements from based on rather complicated logic. Subsequent calls to `#reject!` may remove elements that were not removed on a previous pass. When `#reject!` finally stops finding elements to reject, it will return `nil`. At this point, I would like the loop to stop and the program to proceed. I thought I could do the following: ```rb while array.reject! do |element| ... end end ``` I haven't actually tried it yet, but this construction throws vim's ruby syntax highlighter for a loop (*i.e.,* it thinks the first `do` is for the `while` statement, and thinks the second `end` is actually the end of the encapsulating method). I also tried rewriting this as an inline `while` modifier attached to a `begin...end` block, ```rb begin; end while array.reject! do |element| ... end ``` but it still screws up the highlighting in the same way. In any case, it feels like an abuse of the `while` loop. The only way I could think of to accomplish this is by assigning the method call as a proc: ```rb proc = Proc.new do array.reject! do |element| ... end end while proc.call do; end ``` which works but feels kludgy, especially with the trailing `do; end`. Is there any elegant way to accomplish this??
2017/01/19
[ "https://Stackoverflow.com/questions/41745735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4865822/" ]
Ruby lets you move your condition to the end of the loop statement. This makes it easy to store a result inside of the loop and check it against the conditional: ``` begin any_rejected = arr.reject! { … } end while any_rejected ``` This would work the same as doing `end while arr.reject! { … }`, but it's much clearer here what's happening, especially with a complicated `reject!`.
My personal preference in situations where I need to call a method until the return value is what I want is: ``` :keep_going while my_method ``` Or more tersely I sometimes use: ``` :go while my_method ``` It's one line, and you can use the contents of the symbol to help document what's going on. With your block, I'd personally create a proc/lambda out of it and pass that to reject for clarity. ``` # Harder to follow, IMHO :keep_going while array.reject! do |...| more_code end # Easier to follow, IMHO simplify = ->(...){ ... } :keep_simplifying while array.reject!(&simplify) ```
6,561,828
Greerings all Is there a way to compress data sent from php (server) and then uncompress the data using javascript (client)? Thanking you
2011/07/03
[ "https://Stackoverflow.com/questions/6561828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/447429/" ]
Yes; if you configure your server to serve up the data, which hopefully you are sending in a sane format like JSON, using GZIP compression, then you can just do an Ajax call in JavaScript and it will be automatically decompressed by the browser. To set this up, copy [these lines](https://github.com/paulirish/html5-boilerplate/blob/master/.htaccess#L130-172) into your `.htaccess` file. (I assume you're using Apache, since that is the most common platform for serving PHP.)
If keeping your response overhead small as possible is your goal then [JSON DB: a compressed JSON format](http://peter.michaux.ca/articles/json-db-a-compressed-json-format) might also be of interest to you.
6,561,828
Greerings all Is there a way to compress data sent from php (server) and then uncompress the data using javascript (client)? Thanking you
2011/07/03
[ "https://Stackoverflow.com/questions/6561828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/447429/" ]
I have to agree with @Domenic's answer here. @Nishchay Sharma is way off. The only thing I'll add is if you want to do this on a per-script basis rather than configuring your entire server to compress everything, it's trivial to accomplish your goal by using PHP's gzencode() function coupled with a header call: <http://www.php.net/manual/en/function.gzencode.php> For instance, let's say you are retrieving a huge set of data via an Ajax call to a PHP page. You could configure the PHP page to use gzencode as follows: ``` <?php $someBigString = gzencode('blahblah...blah'); header("Content-type: text/javascript"); header('Content-Encoding: gzip'); echo $someBigString; ?> ``` (This is overly simplified, of course, but I'm keeping it simple.) Your JS Ajax call will pull the data down, see the gzip header, and decompress it automagically. I personally use this technique for very large geo-coordinate data sets for Google Maps that can be many megabytes in size when uncompressed. It couldn't be easier!
Yes; if you configure your server to serve up the data, which hopefully you are sending in a sane format like JSON, using GZIP compression, then you can just do an Ajax call in JavaScript and it will be automatically decompressed by the browser. To set this up, copy [these lines](https://github.com/paulirish/html5-boilerplate/blob/master/.htaccess#L130-172) into your `.htaccess` file. (I assume you're using Apache, since that is the most common platform for serving PHP.)
6,561,828
Greerings all Is there a way to compress data sent from php (server) and then uncompress the data using javascript (client)? Thanking you
2011/07/03
[ "https://Stackoverflow.com/questions/6561828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/447429/" ]
I have to agree with @Domenic's answer here. @Nishchay Sharma is way off. The only thing I'll add is if you want to do this on a per-script basis rather than configuring your entire server to compress everything, it's trivial to accomplish your goal by using PHP's gzencode() function coupled with a header call: <http://www.php.net/manual/en/function.gzencode.php> For instance, let's say you are retrieving a huge set of data via an Ajax call to a PHP page. You could configure the PHP page to use gzencode as follows: ``` <?php $someBigString = gzencode('blahblah...blah'); header("Content-type: text/javascript"); header('Content-Encoding: gzip'); echo $someBigString; ?> ``` (This is overly simplified, of course, but I'm keeping it simple.) Your JS Ajax call will pull the data down, see the gzip header, and decompress it automagically. I personally use this technique for very large geo-coordinate data sets for Google Maps that can be many megabytes in size when uncompressed. It couldn't be easier!
If keeping your response overhead small as possible is your goal then [JSON DB: a compressed JSON format](http://peter.michaux.ca/articles/json-db-a-compressed-json-format) might also be of interest to you.
57,414,152
I have 2 Laravel(5.8) apps. One is a user application, the other is more of an API. The Api has pdfs stored in the storage directory, I need to be able to allow a user to download the pdfs in the other application. Really got no clue how to send the file over from app to the other. The user app makes an api to the api with relevant file ids and things (fine), just can't work out how to send the file back, and then download it on the other end. Tried things like `return response()->stream($pdf)` on the api and `return response()->download($responeFromApiCall)` and loads of other things but really getting nowhere fast. Any advice welcome.
2019/08/08
[ "https://Stackoverflow.com/questions/57414152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3233770/" ]
The laravel code you posted is basically correct, you can use one of `stream()`, `download()` or `file()` helper to serve a file. `file()` ======== Serve a file using a binary response, the most straightforward solution. ```php // optional headers $headers = []; return response()->file(storage_path('myfile.zip'), $optionalHeaders); ``` You can also use your own absolute file path instead of the `storage_path` helper. `download()` ============ The download helper is similar to `file()`, but it also sets a `Content-Disposition` header which will result in a download-popup if you retrieve the file using your browser. ```php $location = storage_path('myfiles/invoice_document.pdf'); // Optional: serve the file under a different filename: $filename = 'mycustomfilename.pdf'; // optional headers $headers = []; return response()->download($location, $filename, $headers); ``` `stream()` ========== The `stream()` helper is a bit more complex and results in reading and serving a file in chunks. This can be used for situations where the filesize is unknown (like passing through another incoming stream from an API). It results in a `Transfer-Encoding: chunked` header which indicates that the data stream is divided into a series of non-overlapping chunks: ```php // optional status code $status = 200; // optional headers $headers = []; // The stream helper requires a callback: return response()->stream(function() { // Load a file from storage. $stream = Storage::readStream('somebigfile.zip'); fpassthru($stream); if(is_resource($stream)) { fclose($stream); } }, $status, $headers); ``` **Note**: `Storage::readStream` takes the default storage disk as defined in `config/filesystems.php`. You can change disks using `Storage::disk('aws')->readStream(...)`. --- Retrieving your served file =========================== Say your file is served under `GET example.com/file`, then another application can retrieve it with curl (assuming PHP). A popular wrapper for this would be `Guzzle`: ```php $client = new \GuzzleHttp\Client(); $file_path = __DIR__ . '/received_file.pdf'; $response = $client->get('http://example.com/file', ['sink' => $file_path]); ``` You can derive the filename and extension from the request itself by the way. If your frontend is javascript, then you can retrieve the file as well but this another component which I dont have one simple example for.
So if I understand correctly you have two systems: user app and api. You want to serve a pdf from user app to the actual user. The user app does a call to api, which works fine. Your issue is converting the response of the api to a response which you can serve from your user app, correct? In that case I'd say you want to proxy the response from the api via the user app to the user. I don't know what the connection between the user app and the api is, but if you use Guzzle you could look at [this answer I posted before](https://stackoverflow.com/a/57261255/7528944).
57,414,152
I have 2 Laravel(5.8) apps. One is a user application, the other is more of an API. The Api has pdfs stored in the storage directory, I need to be able to allow a user to download the pdfs in the other application. Really got no clue how to send the file over from app to the other. The user app makes an api to the api with relevant file ids and things (fine), just can't work out how to send the file back, and then download it on the other end. Tried things like `return response()->stream($pdf)` on the api and `return response()->download($responeFromApiCall)` and loads of other things but really getting nowhere fast. Any advice welcome.
2019/08/08
[ "https://Stackoverflow.com/questions/57414152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3233770/" ]
The laravel code you posted is basically correct, you can use one of `stream()`, `download()` or `file()` helper to serve a file. `file()` ======== Serve a file using a binary response, the most straightforward solution. ```php // optional headers $headers = []; return response()->file(storage_path('myfile.zip'), $optionalHeaders); ``` You can also use your own absolute file path instead of the `storage_path` helper. `download()` ============ The download helper is similar to `file()`, but it also sets a `Content-Disposition` header which will result in a download-popup if you retrieve the file using your browser. ```php $location = storage_path('myfiles/invoice_document.pdf'); // Optional: serve the file under a different filename: $filename = 'mycustomfilename.pdf'; // optional headers $headers = []; return response()->download($location, $filename, $headers); ``` `stream()` ========== The `stream()` helper is a bit more complex and results in reading and serving a file in chunks. This can be used for situations where the filesize is unknown (like passing through another incoming stream from an API). It results in a `Transfer-Encoding: chunked` header which indicates that the data stream is divided into a series of non-overlapping chunks: ```php // optional status code $status = 200; // optional headers $headers = []; // The stream helper requires a callback: return response()->stream(function() { // Load a file from storage. $stream = Storage::readStream('somebigfile.zip'); fpassthru($stream); if(is_resource($stream)) { fclose($stream); } }, $status, $headers); ``` **Note**: `Storage::readStream` takes the default storage disk as defined in `config/filesystems.php`. You can change disks using `Storage::disk('aws')->readStream(...)`. --- Retrieving your served file =========================== Say your file is served under `GET example.com/file`, then another application can retrieve it with curl (assuming PHP). A popular wrapper for this would be `Guzzle`: ```php $client = new \GuzzleHttp\Client(); $file_path = __DIR__ . '/received_file.pdf'; $response = $client->get('http://example.com/file', ['sink' => $file_path]); ``` You can derive the filename and extension from the request itself by the way. If your frontend is javascript, then you can retrieve the file as well but this another component which I dont have one simple example for.
Here are the steps you should follow to get the PDF: 1. Make an API call using AJAX ( you are probably already doing it ) from your public site ( User site ) to the API server, with file ID. 2. API server fetches the PDF, copy it to the public/users/ directory, generate the URL of that PDF file. 3. Send the URL as a response back to the User site. Using JS add a button/ link in the DOM, to that PDF file. **Example**: ``` jQuery.post(ajaxurl, data, function(response) { var responseData = JSON.parse(response); var result = responseData.result; var pdf_path = responseData.pdf_path; $(".nametag-loader").remove(); $(".pdf-download-wrapper").append("<a class='download-link' href='"+ pdf_path +"' target='_blank'>Download</a>"); ``` });
54,703,452
I have huge data frame of multiple columns, one of the column contain data like that ``` No "48.8.1.1." "48.8.1.2." "48.8.2." "48.9." "48.10." "48.11." "48.11.1." "48.11.1.1." "48.11.1.2." "48.11.1.2.2.2.2.1." ``` there is no fixed sequence in sub ordering of data. **PROBLEM :** instead of ``` "48.11.1.2.1." ``` some value are not in correct order like ex: ``` "48.11.1.2.2.2.2.1" ``` no of 2 is extra. How to remove extra numbers of 2. I did try some method like resetting index, etc didn't work. please need some suggestion.
2019/02/15
[ "https://Stackoverflow.com/questions/54703452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8992815/" ]
Use the below code based on Base R ``` X <- c(T,F,T,F,F,T,F,T,T,F,F,F) Y <- as.data.frame(matrix(X,nrow = 6, ncol = 2)) unique(Y$V1) Y$condition <- ifelse(Y$V1 == "TRUE" | Y$V2 == "TRUE","TRUE","FALSE") ```
Here is a possible solution using `apply()` and logical operator `|` that will work for any number of columns of `Y`. ``` result = cbind(Y, apply(Y, 1, FUN = function (x) Reduce(f="|", x))) result # [,1] [,2] [,3] # [1,] TRUE FALSE TRUE # [2,] FALSE TRUE TRUE # [3,] TRUE TRUE TRUE # [4,] FALSE FALSE FALSE # [5,] FALSE FALSE FALSE # [6,] TRUE FALSE TRUE ```
54,703,452
I have huge data frame of multiple columns, one of the column contain data like that ``` No "48.8.1.1." "48.8.1.2." "48.8.2." "48.9." "48.10." "48.11." "48.11.1." "48.11.1.1." "48.11.1.2." "48.11.1.2.2.2.2.1." ``` there is no fixed sequence in sub ordering of data. **PROBLEM :** instead of ``` "48.11.1.2.1." ``` some value are not in correct order like ex: ``` "48.11.1.2.2.2.2.1" ``` no of 2 is extra. How to remove extra numbers of 2. I did try some method like resetting index, etc didn't work. please need some suggestion.
2019/02/15
[ "https://Stackoverflow.com/questions/54703452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8992815/" ]
If you have logical vectors in all the columns, you can use `rowSums` ``` cbind(Y, rowSums(Y) > 0) # [,1] [,2] [,3] #[1,] TRUE FALSE TRUE #[2,] FALSE TRUE TRUE #[3,] TRUE TRUE TRUE #[4,] FALSE FALSE FALSE #[5,] FALSE FALSE FALSE #[6,] TRUE FALSE TRUE ``` This will return `TRUE` if there is at least 1 `TRUE` in any of the row and `FALSE` otherwise. This would also work for any number of columns.
Use the below code based on Base R ``` X <- c(T,F,T,F,F,T,F,T,T,F,F,F) Y <- as.data.frame(matrix(X,nrow = 6, ncol = 2)) unique(Y$V1) Y$condition <- ifelse(Y$V1 == "TRUE" | Y$V2 == "TRUE","TRUE","FALSE") ```
54,703,452
I have huge data frame of multiple columns, one of the column contain data like that ``` No "48.8.1.1." "48.8.1.2." "48.8.2." "48.9." "48.10." "48.11." "48.11.1." "48.11.1.1." "48.11.1.2." "48.11.1.2.2.2.2.1." ``` there is no fixed sequence in sub ordering of data. **PROBLEM :** instead of ``` "48.11.1.2.1." ``` some value are not in correct order like ex: ``` "48.11.1.2.2.2.2.1" ``` no of 2 is extra. How to remove extra numbers of 2. I did try some method like resetting index, etc didn't work. please need some suggestion.
2019/02/15
[ "https://Stackoverflow.com/questions/54703452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8992815/" ]
If you have logical vectors in all the columns, you can use `rowSums` ``` cbind(Y, rowSums(Y) > 0) # [,1] [,2] [,3] #[1,] TRUE FALSE TRUE #[2,] FALSE TRUE TRUE #[3,] TRUE TRUE TRUE #[4,] FALSE FALSE FALSE #[5,] FALSE FALSE FALSE #[6,] TRUE FALSE TRUE ``` This will return `TRUE` if there is at least 1 `TRUE` in any of the row and `FALSE` otherwise. This would also work for any number of columns.
Here is a possible solution using `apply()` and logical operator `|` that will work for any number of columns of `Y`. ``` result = cbind(Y, apply(Y, 1, FUN = function (x) Reduce(f="|", x))) result # [,1] [,2] [,3] # [1,] TRUE FALSE TRUE # [2,] FALSE TRUE TRUE # [3,] TRUE TRUE TRUE # [4,] FALSE FALSE FALSE # [5,] FALSE FALSE FALSE # [6,] TRUE FALSE TRUE ```
261,515
I have a large set of files, some of which contain special characters in the filename (e.g. ä,ö,%, and others). I'd like a script file to iterate over these files and rename them removing the special characters. I don't really mind what it does, but it could replace them with underscores for example e.g. Störung%20.doc would be renamed to St\_rung\_20.doc In order of preference: 1. A Windiws batch file 2. A Windows script file to run with cscript (vbs) 3. A third party piece of software that can be run from the command-line (i.e. no user interaction required) 4. Another language script file, for which I'd have to install an additional script engine Background: I'm trying to encrypt these file with GnuPG on Windows but it doesn't seem to handle special characters in filenames with the --encrypt-files option.
2008/11/04
[ "https://Stackoverflow.com/questions/261515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9625/" ]
Have you tried setting cmd.exe into another codepage before you feed the file names to gnupg? Issue `chcp 65001` to set cmd.exe to Unicode beforehand and try again. If that fails, the following VBScript would do it: ```vb Option Explicit Dim fso: Set fso = CreateObject("Scripting.FileSystemObject") Dim invalidChars: Set invalidChars = New RegExp ' put all characters that you want to strip inside the brackets invalidChars.Pattern = "[äöüß&%]" invalidChars.IgnoreCase = True invalidChars.Global = True If WScript.Arguments.Unnamed.Count = 0 Then WScript.Echo "Please give folder name as argument 1." WScript.Quit 1 End If Recurse fso.GetFolder(WScript.Arguments.Unnamed(0)) Sub Recurse(f) Dim item For Each item In f.SubFolders Recurse item Sanitize item Next For Each item In f.Files Sanitize item Next End Sub Sub Sanitize(folderOrFile) Dim newName: newName = invalidChars.Replace(folderOrFile.Name, "_") If folderOrFile.Name = newName Then Exit Sub WScript.Echo folderOrFile.Name, " -> ", newName folderOrFile.Name = newName End Sub ``` call it like this: ``` cscript replace.vbs "c:\path\to\my\files" ``` You can also drag&drop a folder onto it in Windows Explorer.
From <http://www.robvanderwoude.com/bht.html>: use NT's SET's string substitution to replace or remove characters anywhere in a string: ``` SET STRING=[ABCDEFG] SET STRING=%STRING:[=% SET STRING=%STRING:]=% ECHO String: %STRING% will display String: ABCDEFG SET STRING=[ABCDEFG] SET STRING=%STRING:[=(% SET STRING=%STRING:]=)% ECHO String: %STRING% will display String: (ABCDEFG) SET STRING=[ABCDEFG] SET STRING=%STRING:~1,7% ECHO String: %STRING% will display String: ABCDEFG ``` If you use this attempt, you will have to process each character you want to replace (e.g. Ä,Ö,Ü,ä,ö,ü,ß, but also á,à,é,è...) seperately.
261,515
I have a large set of files, some of which contain special characters in the filename (e.g. ä,ö,%, and others). I'd like a script file to iterate over these files and rename them removing the special characters. I don't really mind what it does, but it could replace them with underscores for example e.g. Störung%20.doc would be renamed to St\_rung\_20.doc In order of preference: 1. A Windiws batch file 2. A Windows script file to run with cscript (vbs) 3. A third party piece of software that can be run from the command-line (i.e. no user interaction required) 4. Another language script file, for which I'd have to install an additional script engine Background: I'm trying to encrypt these file with GnuPG on Windows but it doesn't seem to handle special characters in filenames with the --encrypt-files option.
2008/11/04
[ "https://Stackoverflow.com/questions/261515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9625/" ]
Have you tried setting cmd.exe into another codepage before you feed the file names to gnupg? Issue `chcp 65001` to set cmd.exe to Unicode beforehand and try again. If that fails, the following VBScript would do it: ```vb Option Explicit Dim fso: Set fso = CreateObject("Scripting.FileSystemObject") Dim invalidChars: Set invalidChars = New RegExp ' put all characters that you want to strip inside the brackets invalidChars.Pattern = "[äöüß&%]" invalidChars.IgnoreCase = True invalidChars.Global = True If WScript.Arguments.Unnamed.Count = 0 Then WScript.Echo "Please give folder name as argument 1." WScript.Quit 1 End If Recurse fso.GetFolder(WScript.Arguments.Unnamed(0)) Sub Recurse(f) Dim item For Each item In f.SubFolders Recurse item Sanitize item Next For Each item In f.Files Sanitize item Next End Sub Sub Sanitize(folderOrFile) Dim newName: newName = invalidChars.Replace(folderOrFile.Name, "_") If folderOrFile.Name = newName Then Exit Sub WScript.Echo folderOrFile.Name, " -> ", newName folderOrFile.Name = newName End Sub ``` call it like this: ``` cscript replace.vbs "c:\path\to\my\files" ``` You can also drag&drop a folder onto it in Windows Explorer.
Following 'RenameFilesWithAccentedAndDiacriticalLatinChars.pl' PERL script renames files with accented and diacritical Latin characters : * This PERL script starts from the folder given in parameter, or else from the current folder. * It recursively searches for files with characters belonging to 80 - FF of CP 1250, CP 1252, CP 1254 and CP 1257 (mostly accented Latin characters) or Latin characters having diacritical marks. * It calculates new file names by removing the accents and diacritical marks only from Latin characters (For example, Été --> Ete). * It displays all proposed renaming and perhaps conflicts, and asks the user for global approval. * If the user has approved, it renames all files having no conflict. Option '--batch' avoids interactive questions. Use with care. Option '--' avoids the next parameter to be interpreted as option. **Special Warning** : * This script was originally encoded in UTF-8, and should stay so. * This script may rename a lot of files. * Files names are theoretically all encoded only with UTF-8. But some file names may be found to contain also some characters having legacy encoding. * The author has applied efforts for consistency checks, robustness, conflict detection and use of appropriate encoding. So this script should only rename files by removing accents and diacritical marks from Latin characters. * But this script has been tested only under a limited number of OS (Windows, Mac OS X, Linux) and a limited number of terminal encodings (CP 850, ISO-8859-1, UTF-8). * So, under weird circumstances, this script could rename many files with random names. * Therefore, this script should be used with care, and modified with extreme care (beware encoding of internal strings, inputs, outputs and commands) ``` #!/usr/bin/perl -w #============================================================================= # # Copyright 2010 Etienne URBAH # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details at # http://www.gnu.org/licenses/gpl.html # # For usage and SPECIAL WARNING, see the 'Help' section below. # #============================================================================= use 5.008_000; # For correct Unicode support use warnings; use strict; use Encode; $| = 1; # Autoflush STDOUT #----------------------------------------------------------------------------- # Function ucRemoveEolUnderscoreDash : # Set Uppercase, remove End of line, Underscores and Dashes #----------------------------------------------------------------------------- sub ucRemoveEolUnderscoreDash { local $_ = uc($_[0]); chomp; tr/_\-//d; $_; } #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- my $Encoding_Western = 'ISO-8859-1'; my $Encoding_Central = 'ISO-8859-2'; my $Encoding_Baltic = 'ISO-8859-4'; my $Encoding_Turkish = 'ISO-8859-9'; my $Encoding_W_Euro = 'ISO-8859-15'; my $Code_Page_OldWest = 850; my $Code_Page_Central = 1250; my $Code_Page_Western = 1252; my $Code_Page_Turkish = 1254; my $Code_Page_Baltic = 1257; my $Code_Page_UTF8 = 65001; my $HighBitSetChars = pack('C*', 0x80..0xFF); my %SuperEncodings = ( &ucRemoveEolUnderscoreDash($Encoding_Western), 'cp'.$Code_Page_Western, &ucRemoveEolUnderscoreDash($Encoding_Central), 'cp'.$Code_Page_Central, &ucRemoveEolUnderscoreDash($Encoding_Baltic), 'cp'.$Code_Page_Baltic, &ucRemoveEolUnderscoreDash($Encoding_Turkish), 'cp'.$Code_Page_Turkish, &ucRemoveEolUnderscoreDash($Encoding_W_Euro), 'cp'.$Code_Page_Western, &ucRemoveEolUnderscoreDash('cp'.$Code_Page_OldWest), 'cp'.$Code_Page_Western ); my %EncodingNames = ( 'cp'.$Code_Page_Central, 'Central European', 'cp'.$Code_Page_Western, 'Western European', 'cp'.$Code_Page_Turkish, ' Turkish ', 'cp'.$Code_Page_Baltic, ' Baltic ' ); my %NonAccenChars = ( #--------------------------------# 'cp'.$Code_Page_Central, # Central European (cp1250) # #--------------------------------# #€_‚_„…†‡_‰Š‹ŚŤŽŹ_‘’“”•–—_™š›śťžź# 'E_,_,.++_%S_STZZ_````.--_Ts_stzz'. # ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľż# '_``LoAlS`CS_--RZ`+,l`uP.,as_L~lz'. #ŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢß# 'RAAAALCCCEEEEIIDDNNOOOOxRUUUUYTS'. #ŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙# 'raaaalccceeeeiiddnnoooo%ruuuuyt`', #--------------------------------# 'cp'.$Code_Page_Western, # Western European (cp1252) # #--------------------------------# #€_‚ƒ„…†‡ˆ‰Š‹Œ_Ž__‘’“”•–—˜™š›œ_žŸ# 'E_,f,.++^%S_O_Z__````.--~Ts_o_zY'. # ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿# '_!cLoYlS`Ca_--R-`+23`uP.,10_qh3_'. #ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞß# 'AAAAAAACEEEEIIIIDNOOOOOxOUUUUYTS'. #àáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ# 'aaaaaaaceeeeiiiidnooooo%ouuuuyty', #--------------------------------# 'cp'.$Code_Page_Turkish, # Turkish (cp1254) # #--------------------------------# #€_‚ƒ„…†‡ˆ‰Š‹Œ____‘’“”•–—˜™š›œ__Ÿ# 'E_,f,.++^%S_O____````.--~Ts_o__Y'. # ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿# '_!cLoYlS`Ca_--R-`+23`uP.,10_qh3_'. #ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞß# 'AAAAAAACEEEEIIIIGNOOOOOxOUUUUISS'. #àáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ# 'aaaaaaaceeeeiiiignooooo%ouuuuisy', #--------------------------------# 'cp'.$Code_Page_Baltic, # Baltic (cp1257) # #--------------------------------# #€_‚_„…†‡_‰_‹_¨ˇ¸_‘’“”•–—_™_›_¯˛_# 'E_,_,.++_%___``,_````.--_T___-,_'. # �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æ# '__cLo_lSOCR_--RA`+23`uP.o1r_qh3a'. #ĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽß# 'AIACAAEECEZEGKILSNNOOOOxULSUUZZS'. #ąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙# 'aiacaaeecezegkilsnnoooo%ulsuuzz`' ); my %AccentedChars; my $AccentedChars = ''; my $NonAccenChars = ''; for ( $Code_Page_Central, $Code_Page_Western, $Code_Page_Turkish, $Code_Page_Baltic ) { $AccentedChars{'cp'.$_} = decode('cp'.$_, $HighBitSetChars); $AccentedChars .= $AccentedChars{'cp'.$_}; $NonAccenChars .= $NonAccenChars{'cp'.$_}; } #print "\n", length($NonAccenChars), ' ', $NonAccenChars,"\n"; #print "\n", length($AccentedChars), ' ', $AccentedChars,"\n"; my $QuotedMetaNonAccenChars = quotemeta($NonAccenChars); my $DiacriticalChars = ''; for ( 0x0300..0x036F, 0x1DC0..0x1DFF ) { $DiacriticalChars .= chr($_) } #----------------------------------------------------------------------------- # Parse options and parameters #----------------------------------------------------------------------------- my $b_Help = 0; my $b_Interactive = 1; my $b_UTF8 = 0; my $b_Parameter = 0; my $Folder; for ( @ARGV ) { if ( lc($_) eq '--' ) { $b_Parameter = 1 } elsif ( (not $b_Parameter) and (lc($_) eq '--batch') ) { $b_Interactive = 0 } elsif ( (not $b_Parameter) and (lc($_) eq '--utf8') ) { $b_UTF8 = 1 } elsif ( $b_Parameter or (substr($_, 0, 1) ne '-') ) { if ( defined($Folder) ) { die "$0 accepts only 1 parameter\n" } else { $Folder = $_ } } else { $b_Help = 1 } } #----------------------------------------------------------------------------- # Help #----------------------------------------------------------------------------- if ( $b_Help ) { die << "END_OF_HELP" $0 [--help] [--batch] [--] [folder] This script renames files with accented and diacritical Latin characters : - This PERL script starts from the folder given in parameter, or else from the current folder. - It recursively searches for files with characters belonging to 80 - FF of CP 1250, CP 1252, CP 1254 and CP 1257 (mostly accented Latin characters) or Latin characters having diacritical marks. - It calculates new file names by removing the accents and diacritical marks only from Latin characters (For example, Été --> Ete). - It displays all proposed renaming and perhaps conflicts, and asks the user for global approval. - If the user has approved, it renames all files having no conflict. Option '--batch' avoids interactive questions. Use with care. Option '--' avoids the next parameter to be interpreted as option. SPECIAL WARNING : - This script was originally encoded in UTF-8, and should stay so. - This script may rename a lot of files. - Files names are theoretically all encoded only with UTF-8. But some file names may be found to contain also some characters having legacy encoding. - The author has applied efforts for consistency checks, robustness, conflict detection and use of appropriate encoding. So this script should only rename files by removing accents and diacritical marks from Latin characters. - But this script has been tested only under a limited number of OS (Windows, Mac OS X, Linux) and a limited number of terminal encodings (CP 850, ISO-8859-1, UTF-8). - So, under weird circumstances, this script could rename many files with random names. - Therefore, this script should be used with care, and modified with extreme care (beware encoding of internal strings, inputs, outputs and commands) END_OF_HELP } #----------------------------------------------------------------------------- # If requested, change current folder #----------------------------------------------------------------------------- if ( defined($Folder) ) { chdir($Folder) or die "Can NOT set '$Folder' as current folder\n" } #----------------------------------------------------------------------------- # Following instruction is MANDATORY. # The return value should be non-zero, but on some systems it is zero. #----------------------------------------------------------------------------- utf8::decode($AccentedChars); # or die "$0: '\$AccentedChars' should be UTF-8 but is NOT.\n"; #----------------------------------------------------------------------------- # Check consistency on 'tr' #----------------------------------------------------------------------------- $_ = $AccentedChars; eval "tr/$AccentedChars/$QuotedMetaNonAccenChars/"; if ( $@ ) { warn $@ } if ( $@ or ($_ ne $NonAccenChars) ) { die "$0: Consistency check on 'tr' FAILED :\n\n", "Translated Accented Chars : ", length($_), ' : ', $_, "\n\n", " Non Accented Chars : ", length($NonAccenChars), ' : ', $NonAccenChars, "\n" } #----------------------------------------------------------------------------- # Constants depending on the OS #----------------------------------------------------------------------------- my $b_Windows = ( defined($ENV{'OS'}) and ($ENV{'OS'} eq 'Windows_NT') ); my ($Q, $sep, $sep2, $HOME, $Find, @List, $cwd, @Move); if ( $b_Windows ) { $Q = '"'; $sep = '\\'; $sep2 = '\\\\'; $HOME = $ENV{'USERPROFILE'}; $Find = 'dir /b /s'; @List = ( ( (`ver 2>&1` =~ m/version\s+([0-9]+)/i) and ($1 >= 6) ) ? ('icacls') : ( 'cacls') ); $cwd = `cd`; chomp $cwd; $cwd = quotemeta($cwd); @Move = ('move'); } else { $Q = "'"; $sep = '/'; $sep2 = '/'; $HOME = $ENV{'HOME'}; $Find = 'find .'; @List = ('ls', '-d', '--'); @Move = ('mv', '--'); if ( -w '/bin' ) { die "$0: For safety reasons, ", "usage is BLOCKED to administrators.\n"} } my $Encoding; my $ucEncoding; my $InputPipe = '-|'; # Used as global variable #----------------------------------------------------------------------------- # Under Windows, associate input and output encodings to code pages : # - Get the original code page, # - If it is not UTF-8, try to set it to UTF-8, # - Define the input encoding as the one associated to the ACTIVE code page, # - If STDOUT is the console, encode output for the ORIGINAL code page. #----------------------------------------------------------------------------- my $Code_Page_Original; my $Code_Page_Active; if ( $b_Windows ) { #----------------------------------------------------------------------- # Get the original code page #----------------------------------------------------------------------- $_ = `chcp`; m/([0-9]+)$/ or die "Non numeric Windows code page : ", $_; $Code_Page_Original = $1; print 'Windows Original Code Page = ', $Code_Page_Original, ( $Code_Page_Original == $Code_Page_UTF8 ? ' = UTF-8, display is perhaps correct with a true type font.' : '' ), "\n\n"; $Code_Page_Active = $Code_Page_Original ; #----------------------------------------------------------------------- # The input encoding must be the same as the ACTIVE code page #----------------------------------------------------------------------- $Encoding = ( $Code_Page_Active == $Code_Page_UTF8 ? 'utf8' : 'cp'.$Code_Page_Active ) ; $InputPipe .= ":encoding($Encoding)"; print "InputPipe = '$InputPipe'\n\n"; #----------------------------------------------------------------------- # If STDOUT is the console, output encoding must be the same as the # ORIGINAL code page #----------------------------------------------------------------------- if ( $Code_Page_Original != $Code_Page_UTF8 ) { no warnings 'unopened'; @_ = stat(STDOUT); use warnings; if ( scalar(@_) and ($_[0] == 1) ) { binmode(STDOUT, ":encoding(cp$Code_Page_Original)") } else { binmode(STDOUT, ":encoding($Encoding)") } } } #----------------------------------------------------------------------------- # Under *nix, if the 'LANG' environment variable contains an encoding, # verify that this encoding is supported by the OS and by PERL. #----------------------------------------------------------------------------- elsif ( defined($ENV{'LANG'}) and ($ENV{'LANG'} =~ m/\.([^\@]+)$/i) ) { $Encoding = $1; my $Kernel = `uname -s`; chomp $Kernel; my $ucEncoding = &ucRemoveEolUnderscoreDash($Encoding); if ( (lc($Kernel) ne 'darwin') and not grep {$_ eq $ucEncoding} ( map { ($_, &ucRemoveEolUnderscoreDash($_)) } `locale -m` ) ) { die "Encoding = '$Encoding' or '$ucEncoding' NOT supported ". "by the OS\n" } my $ucLocale = &ucRemoveEolUnderscoreDash($ENV{'LANG'}); if ( not grep {$_ eq $ucLocale} ( map { ($_, &ucRemoveEolUnderscoreDash($_)) } `locale -a` ) ) { die "Locale = '$ENV{LANG}' or '$ucLocale' NOT supported ". "by the OS\n" } if ( not defined(Encode::find_encoding($Encoding)) ) { die "Encoding = '$Encoding' or '$ucEncoding' NOT supported ". "by PERL\n" } print "Encoding = '$Encoding' is supported by the OS and PERL\n\n"; binmode(STDOUT, ":encoding($Encoding)"); } #----------------------------------------------------------------------------- # Check consistency between parameter of 'echo' and output of 'echo' #----------------------------------------------------------------------------- undef $_; if ( defined($Encoding) ) { $ucEncoding = &ucRemoveEolUnderscoreDash($Encoding); if ( defined($SuperEncodings{$ucEncoding}) ) { $_ = substr($AccentedChars{$SuperEncodings{$ucEncoding}}, 0x20, 0x60) } elsif ( defined($AccentedChars{$Encoding}) ) { $_ = $AccentedChars{$Encoding} } elsif ( $Encoding =~ m/^utf-?8$/i ) { $_ = $AccentedChars } } if ( not defined($_) ) # Chosen chars are same in 4 code pages { $_ = decode('cp'.$Code_Page_Central, pack('C*', 0xC9, 0xD3, 0xD7, 0xDC, # ÉÓ×Ü 0xE9, 0xF3, 0xF7, 0xFC)) } # éó÷ü #print $_, " (Parameter)\n\n"; #system 'echo', $_; utf8::decode($_); #print "\n", $_, " (Parameter after utf8::decode)\n\n"; my @EchoCommand = ( $b_Windows ? "echo $_" : ('echo', $_) ); #system @EchoCommand; open(ECHO, $InputPipe, @EchoCommand) or die 'echo $_: ', $!; my $Output = join('', <ECHO>); close(ECHO); chomp $Output; #print "\n", $Output, " (Output of 'echo')\n"; utf8::decode($Output); #print "\n", $Output, " (Output of 'echo' after utf8::decode)\n\n"; if ( $Output ne $_ ) { warn "$0: Consistency check between parameter ", "of 'echo' and output of 'echo' FAILED :\n\n", "Parameter of 'echo' : ", length($_), ' : ', $_, "\n\n", " Output of 'echo' : ", length($Output), ' : ', $Output, "\n"; exit 1; } #----------------------------------------------------------------------------- # Print the translation table #----------------------------------------------------------------------------- if ( defined($Encoding) ) { undef $_; $ucEncoding = &ucRemoveEolUnderscoreDash($Encoding); if ( defined($SuperEncodings{$ucEncoding}) ) { $_ = $SuperEncodings{$ucEncoding}; print "--------- $EncodingNames{$_} ---------\n", ' ', substr($AccentedChars{$_}, 0x20, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x20, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x40, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x40, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x60, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x60, 0x20), "\n\n" } else { for ( 'cp'.$Code_Page_Central, 'cp'.$Code_Page_Western, 'cp'.$Code_Page_Turkish, 'cp'.$Code_Page_Baltic ) { if ( ('cp'.$Encoding eq $_) or ($Encoding =~ m/^utf-?8$/i) ) { print "--------- $EncodingNames{$_} ---------\n", ' ', substr($AccentedChars{$_}, 0, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x20, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x20, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x40, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x40, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x60, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x60, 0x20), "\n\n" } } } } #----------------------------------------------------------------------------- # Completely optional : # Inside the Unison file, find the accented file names to ignore #----------------------------------------------------------------------------- my $UnisonFile = $HOME.$sep.'.unison'.$sep.'common.unison'; my @Ignores; if ( open(UnisonFile, '<', $UnisonFile) ) { print "\nUnison File '", $UnisonFile, "'\n"; while ( <UnisonFile> ) { if ( m/^\s*ignore\s*=\s*Name\s*(.+)/ ) { $_ = $1 ; if ( m/[$AccentedChars]/ ) { push(@Ignores, $_) } } } close(UnisonFile); } print map(" Ignore: ".$_."\n", @Ignores); #----------------------------------------------------------------------------- # Function OutputAndErrorFromCommand : # # Execute the command given as array in parameter, and return STDOUT + STDERR # # Reads global variable $InputPipe #----------------------------------------------------------------------------- sub OutputAndErrorFromCommand { local $_; my @Command = @_; # Protects content of @_ from any modification #--------------------------------------------------------------------------- # Under Windows, fork fails, so : # - Enclose into double quotes parameters containing blanks or simple # quotes, # - Use piped open with redirection of STDERR. #--------------------------------------------------------------------------- if ( defined($ENV{'OS'}) and ($ENV{'OS'} eq 'Windows_NT') ) { for ( @Command ) { s/^((-|.*(\s|')).*)$/$Q$1$Q/ } my $Command = join(' ', @Command); #print "\n", $Command; open(COMMAND, $InputPipe, "$Command 2>&1") or die '$Command: ', $!; } #--------------------------------------------------------------------------- # Under Unix, quoting is too difficult, but fork succeeds #--------------------------------------------------------------------------- else { my $pid = open(COMMAND, $InputPipe); defined($pid) or die "Can't fork: $!"; if ( $pid == 0 ) # Child process { open STDERR, '>&=STDOUT'; exec @Command; # Returns only on failure die "Can't @Command"; } } $_ = join('', <COMMAND>); # Child's STDOUT + STDERR close COMMAND; chomp; utf8::decode($_); $_; } #----------------------------------------------------------------------------- # Find recursively all files inside the current folder. # Verify accessibility of files with accented names. # Calculate non-accented file names from accented file names. # Build the list of duplicates. #----------------------------------------------------------------------------- my %Olds; # $Olds{$New} = [ $Old1, $Old2, ... ] my $Old; my $Dir; my $Command; my $ErrorMessage; my $New; my %News; print "\n\nFiles with accented name and the corresponding non-accented name ", ":\n"; open(FIND, $InputPipe, $Find) or die $Find, ': ', $!; FILE: while ( <FIND> ) { chomp; #--------------------------------------------------------------------------- # If the file path contains UTF-8, following instruction is MANDATORY. # If the file path does NOT contain UTF-8, it should NOT hurt. #--------------------------------------------------------------------------- utf8::decode($_); if ( $b_Windows ) { s/^$cwd$sep2// } else { s/^\.$sep2// } #--------------------------------------------------------------------------- # From now on : $_ = Dir/OldFilename #--------------------------------------------------------------------------- push(@{$Olds{$_}}, $_); if ( m/([^$sep2]+)$/ and ($1 =~ m/[$AccentedChars]|([\ -\~][$DiacriticalChars])/) ) { if ( $b_Windows and m/$Q/ ) { print "\n $Q$_$Q\n*** contains quotes.\n"; next; } for my $Ignore ( @Ignores ) { if ( m/$Ignore$/ ) { next FILE } } $Old = $_ ; m/^(.*$sep2)?([^$sep2]+)$/; $Dir = ( defined($1) ? $1 : ''); $_ = $2; #--------------------------------------------------------------------- # From now on : $Old = Dir/OldFilename # $_ = OldFilename #--------------------------------------------------------------------- print "\n $Q$Old$Q\n"; $ErrorMessage = &OutputAndErrorFromCommand(@List, $Old); if ( $? != 0 ) { print "*** $ErrorMessage\n" } else { #--------------------------------------------------------------- # Change accented Latin chars to non-accented chars. # Remove all diacritical marks after Latin chars. #--------------------------------------------------------------- eval "tr/$AccentedChars/$QuotedMetaNonAccenChars/"; s/([\ -\~])[$DiacriticalChars]+/$1/g; #--------------------------------------------------------------- # From now on : $Old = Dir/OldFilename # $_ = NewFilename #--------------------------------------------------------------- if ( $@ ) { warn $@ } else { $New = $Dir.$_; if ( $b_Windows or (not utf8::is_utf8($Dir)) ) # Weird { utf8::decode($New) } # but necessary $News{$Old} = $New; push(@{$Olds{$New}}, $Old); } print "--> $Q$Dir$_$Q\n"; } } } close(FIND); #----------------------------------------------------------------------------- # Print list of duplicate non-accented file names #----------------------------------------------------------------------------- my $b_NoDuplicate = 1; for my $New ( sort keys %Olds ) { if ( scalar(@{$Olds{$New}}) > 1 ) { if ( $b_NoDuplicate ) { print "\n\nFollowing files would have same non-accented name ", ":\n"; $b_NoDuplicate = 0; } print "\n", map(' '.$_."\n", @{$Olds{$New}}), '--> ', $New, "\n"; for ( @{$Olds{$New}} ) { delete $News{$_} }; } } #----------------------------------------------------------------------------- # If there are NO file to rename, then exit #----------------------------------------------------------------------------- my $Number = scalar(keys %News); print "\n\n"; if ( $Number < 1 ) { print "There are NO file to rename\n"; exit; } #----------------------------------------------------------------------------- # Ask the user for global approval of renaming #----------------------------------------------------------------------------- if ( $b_Interactive ) { print "In order to really rename the ", $Number, " files which can safely be renamed, type 'rename' : "; $_ = <STDIN>; sleep 1; # Gives time to PERL to handle interrupts if ( not m/^rename$/i ) { exit 1 } } else { print $Number, " files will be renamed\n\n" } #----------------------------------------------------------------------------- # Rename accented file names sorted descending by name size #----------------------------------------------------------------------------- $Number = 0; my $Move = join(' ', @Move); for ( sort {length($b) <=> length($a)} keys %News ) { $ErrorMessage = &OutputAndErrorFromCommand(@Move, $_, $News{$_}); if ( $? == 0 ) { $Number++ } else { print "\n$Move $Q$_$Q\n", (' ' x length($Move)), " $Q$News{$_}$Q\n", ('*' x length($Move)), " $ErrorMessage\n" } } print "\n$Number files have been successfully renamed\n"; __END__ ```
261,515
I have a large set of files, some of which contain special characters in the filename (e.g. ä,ö,%, and others). I'd like a script file to iterate over these files and rename them removing the special characters. I don't really mind what it does, but it could replace them with underscores for example e.g. Störung%20.doc would be renamed to St\_rung\_20.doc In order of preference: 1. A Windiws batch file 2. A Windows script file to run with cscript (vbs) 3. A third party piece of software that can be run from the command-line (i.e. no user interaction required) 4. Another language script file, for which I'd have to install an additional script engine Background: I'm trying to encrypt these file with GnuPG on Windows but it doesn't seem to handle special characters in filenames with the --encrypt-files option.
2008/11/04
[ "https://Stackoverflow.com/questions/261515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9625/" ]
Have you tried setting cmd.exe into another codepage before you feed the file names to gnupg? Issue `chcp 65001` to set cmd.exe to Unicode beforehand and try again. If that fails, the following VBScript would do it: ```vb Option Explicit Dim fso: Set fso = CreateObject("Scripting.FileSystemObject") Dim invalidChars: Set invalidChars = New RegExp ' put all characters that you want to strip inside the brackets invalidChars.Pattern = "[äöüß&%]" invalidChars.IgnoreCase = True invalidChars.Global = True If WScript.Arguments.Unnamed.Count = 0 Then WScript.Echo "Please give folder name as argument 1." WScript.Quit 1 End If Recurse fso.GetFolder(WScript.Arguments.Unnamed(0)) Sub Recurse(f) Dim item For Each item In f.SubFolders Recurse item Sanitize item Next For Each item In f.Files Sanitize item Next End Sub Sub Sanitize(folderOrFile) Dim newName: newName = invalidChars.Replace(folderOrFile.Name, "_") If folderOrFile.Name = newName Then Exit Sub WScript.Echo folderOrFile.Name, " -> ", newName folderOrFile.Name = newName End Sub ``` call it like this: ``` cscript replace.vbs "c:\path\to\my\files" ``` You can also drag&drop a folder onto it in Windows Explorer.
I'm using this batch to rename folders and seems to work fine so far... In my case codepage is 1252, yours might be different. ``` mode con codepage select=1252 @echo off Setlocal enabledelayedexpansion ::folder only (/D option) for /R /D %%d in (*) do ( set an=%%~nd set bn=!an:.=_! set cn=!bn:-=_! set dn=!cn: =_! set en=!dn:Á=A! set fn=!en:É=E! set gn=!fn:Í=I! set hn=!gn:Ó=O! set in=!hn:Ú=U! set jn=!in:Ü=U! set kn=!jn:á=a! set ln=!kn:é=e! set mn=!ln:í=i! set nn=!mn:ó=o! set on=!nn:ú=u! set pn=!on:ü=u! set qn=!pn:Ñ=N! set zn=!on:ñ=n! set ax=%%~xd set bx=!ax:.=_! set cx=!bx:-=_! set dx=!cx: =_! set bx=!ax:.=_! set cx=!bx:-=_! set dx=!cx: =_! set ex=!dx:Á=A! set fx=!ex:É=E! set gx=!fx:Í=I! set hx=!gx:Ó=O! set ix=!hx:Ú=U! set jx=!ix:Ü=U! set kx=!jx:á=a! set lx=!kx:é=e! set mx=!lx:í=i! set nx=!mx:ó=o! set ox=!nx:ú=u! set px=!ox:ü=u! set qx=!px:Ñ=N! set zx=!ox:ñ=n! if [!an!]==[] (set zn=) if [!ax!]==[] (set zx=) set newname=!zn!!zx! if /i not [%%~nd%%~xd]==[!newname!] rename "%%d" !newname! ) endlocal pause ```
261,515
I have a large set of files, some of which contain special characters in the filename (e.g. ä,ö,%, and others). I'd like a script file to iterate over these files and rename them removing the special characters. I don't really mind what it does, but it could replace them with underscores for example e.g. Störung%20.doc would be renamed to St\_rung\_20.doc In order of preference: 1. A Windiws batch file 2. A Windows script file to run with cscript (vbs) 3. A third party piece of software that can be run from the command-line (i.e. no user interaction required) 4. Another language script file, for which I'd have to install an additional script engine Background: I'm trying to encrypt these file with GnuPG on Windows but it doesn't seem to handle special characters in filenames with the --encrypt-files option.
2008/11/04
[ "https://Stackoverflow.com/questions/261515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9625/" ]
Thanks to Tomalak who actually pointed me in the right direction. Thought I'd post here for completeness. The problem seems to be that the codepage used by GPG is fixed (Latin I) independent of the codepage configured in the console. But once he pointed this out, I figured out how to workaraound this. The trick is to change the codepage before generating the file list. This will actually make the filelist appear to be incorrect when viewed in the console. However, when passed to GPG, it works fine. GPG accepts the files and spits out the encrytped files with correct filenames. The batch file looks something like this: ``` chcp 1252 dir /b /s /a-d MyFolder >filelist.txt gpg -r [email protected] --encrypt-files <filelist.txt ```
From <http://www.robvanderwoude.com/bht.html>: use NT's SET's string substitution to replace or remove characters anywhere in a string: ``` SET STRING=[ABCDEFG] SET STRING=%STRING:[=% SET STRING=%STRING:]=% ECHO String: %STRING% will display String: ABCDEFG SET STRING=[ABCDEFG] SET STRING=%STRING:[=(% SET STRING=%STRING:]=)% ECHO String: %STRING% will display String: (ABCDEFG) SET STRING=[ABCDEFG] SET STRING=%STRING:~1,7% ECHO String: %STRING% will display String: ABCDEFG ``` If you use this attempt, you will have to process each character you want to replace (e.g. Ä,Ö,Ü,ä,ö,ü,ß, but also á,à,é,è...) seperately.
261,515
I have a large set of files, some of which contain special characters in the filename (e.g. ä,ö,%, and others). I'd like a script file to iterate over these files and rename them removing the special characters. I don't really mind what it does, but it could replace them with underscores for example e.g. Störung%20.doc would be renamed to St\_rung\_20.doc In order of preference: 1. A Windiws batch file 2. A Windows script file to run with cscript (vbs) 3. A third party piece of software that can be run from the command-line (i.e. no user interaction required) 4. Another language script file, for which I'd have to install an additional script engine Background: I'm trying to encrypt these file with GnuPG on Windows but it doesn't seem to handle special characters in filenames with the --encrypt-files option.
2008/11/04
[ "https://Stackoverflow.com/questions/261515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9625/" ]
From <http://www.robvanderwoude.com/bht.html>: use NT's SET's string substitution to replace or remove characters anywhere in a string: ``` SET STRING=[ABCDEFG] SET STRING=%STRING:[=% SET STRING=%STRING:]=% ECHO String: %STRING% will display String: ABCDEFG SET STRING=[ABCDEFG] SET STRING=%STRING:[=(% SET STRING=%STRING:]=)% ECHO String: %STRING% will display String: (ABCDEFG) SET STRING=[ABCDEFG] SET STRING=%STRING:~1,7% ECHO String: %STRING% will display String: ABCDEFG ``` If you use this attempt, you will have to process each character you want to replace (e.g. Ä,Ö,Ü,ä,ö,ü,ß, but also á,à,é,è...) seperately.
I'm using this batch to rename folders and seems to work fine so far... In my case codepage is 1252, yours might be different. ``` mode con codepage select=1252 @echo off Setlocal enabledelayedexpansion ::folder only (/D option) for /R /D %%d in (*) do ( set an=%%~nd set bn=!an:.=_! set cn=!bn:-=_! set dn=!cn: =_! set en=!dn:Á=A! set fn=!en:É=E! set gn=!fn:Í=I! set hn=!gn:Ó=O! set in=!hn:Ú=U! set jn=!in:Ü=U! set kn=!jn:á=a! set ln=!kn:é=e! set mn=!ln:í=i! set nn=!mn:ó=o! set on=!nn:ú=u! set pn=!on:ü=u! set qn=!pn:Ñ=N! set zn=!on:ñ=n! set ax=%%~xd set bx=!ax:.=_! set cx=!bx:-=_! set dx=!cx: =_! set bx=!ax:.=_! set cx=!bx:-=_! set dx=!cx: =_! set ex=!dx:Á=A! set fx=!ex:É=E! set gx=!fx:Í=I! set hx=!gx:Ó=O! set ix=!hx:Ú=U! set jx=!ix:Ü=U! set kx=!jx:á=a! set lx=!kx:é=e! set mx=!lx:í=i! set nx=!mx:ó=o! set ox=!nx:ú=u! set px=!ox:ü=u! set qx=!px:Ñ=N! set zx=!ox:ñ=n! if [!an!]==[] (set zn=) if [!ax!]==[] (set zx=) set newname=!zn!!zx! if /i not [%%~nd%%~xd]==[!newname!] rename "%%d" !newname! ) endlocal pause ```
261,515
I have a large set of files, some of which contain special characters in the filename (e.g. ä,ö,%, and others). I'd like a script file to iterate over these files and rename them removing the special characters. I don't really mind what it does, but it could replace them with underscores for example e.g. Störung%20.doc would be renamed to St\_rung\_20.doc In order of preference: 1. A Windiws batch file 2. A Windows script file to run with cscript (vbs) 3. A third party piece of software that can be run from the command-line (i.e. no user interaction required) 4. Another language script file, for which I'd have to install an additional script engine Background: I'm trying to encrypt these file with GnuPG on Windows but it doesn't seem to handle special characters in filenames with the --encrypt-files option.
2008/11/04
[ "https://Stackoverflow.com/questions/261515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9625/" ]
Thanks to Tomalak who actually pointed me in the right direction. Thought I'd post here for completeness. The problem seems to be that the codepage used by GPG is fixed (Latin I) independent of the codepage configured in the console. But once he pointed this out, I figured out how to workaraound this. The trick is to change the codepage before generating the file list. This will actually make the filelist appear to be incorrect when viewed in the console. However, when passed to GPG, it works fine. GPG accepts the files and spits out the encrytped files with correct filenames. The batch file looks something like this: ``` chcp 1252 dir /b /s /a-d MyFolder >filelist.txt gpg -r [email protected] --encrypt-files <filelist.txt ```
Following 'RenameFilesWithAccentedAndDiacriticalLatinChars.pl' PERL script renames files with accented and diacritical Latin characters : * This PERL script starts from the folder given in parameter, or else from the current folder. * It recursively searches for files with characters belonging to 80 - FF of CP 1250, CP 1252, CP 1254 and CP 1257 (mostly accented Latin characters) or Latin characters having diacritical marks. * It calculates new file names by removing the accents and diacritical marks only from Latin characters (For example, Été --> Ete). * It displays all proposed renaming and perhaps conflicts, and asks the user for global approval. * If the user has approved, it renames all files having no conflict. Option '--batch' avoids interactive questions. Use with care. Option '--' avoids the next parameter to be interpreted as option. **Special Warning** : * This script was originally encoded in UTF-8, and should stay so. * This script may rename a lot of files. * Files names are theoretically all encoded only with UTF-8. But some file names may be found to contain also some characters having legacy encoding. * The author has applied efforts for consistency checks, robustness, conflict detection and use of appropriate encoding. So this script should only rename files by removing accents and diacritical marks from Latin characters. * But this script has been tested only under a limited number of OS (Windows, Mac OS X, Linux) and a limited number of terminal encodings (CP 850, ISO-8859-1, UTF-8). * So, under weird circumstances, this script could rename many files with random names. * Therefore, this script should be used with care, and modified with extreme care (beware encoding of internal strings, inputs, outputs and commands) ``` #!/usr/bin/perl -w #============================================================================= # # Copyright 2010 Etienne URBAH # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details at # http://www.gnu.org/licenses/gpl.html # # For usage and SPECIAL WARNING, see the 'Help' section below. # #============================================================================= use 5.008_000; # For correct Unicode support use warnings; use strict; use Encode; $| = 1; # Autoflush STDOUT #----------------------------------------------------------------------------- # Function ucRemoveEolUnderscoreDash : # Set Uppercase, remove End of line, Underscores and Dashes #----------------------------------------------------------------------------- sub ucRemoveEolUnderscoreDash { local $_ = uc($_[0]); chomp; tr/_\-//d; $_; } #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- my $Encoding_Western = 'ISO-8859-1'; my $Encoding_Central = 'ISO-8859-2'; my $Encoding_Baltic = 'ISO-8859-4'; my $Encoding_Turkish = 'ISO-8859-9'; my $Encoding_W_Euro = 'ISO-8859-15'; my $Code_Page_OldWest = 850; my $Code_Page_Central = 1250; my $Code_Page_Western = 1252; my $Code_Page_Turkish = 1254; my $Code_Page_Baltic = 1257; my $Code_Page_UTF8 = 65001; my $HighBitSetChars = pack('C*', 0x80..0xFF); my %SuperEncodings = ( &ucRemoveEolUnderscoreDash($Encoding_Western), 'cp'.$Code_Page_Western, &ucRemoveEolUnderscoreDash($Encoding_Central), 'cp'.$Code_Page_Central, &ucRemoveEolUnderscoreDash($Encoding_Baltic), 'cp'.$Code_Page_Baltic, &ucRemoveEolUnderscoreDash($Encoding_Turkish), 'cp'.$Code_Page_Turkish, &ucRemoveEolUnderscoreDash($Encoding_W_Euro), 'cp'.$Code_Page_Western, &ucRemoveEolUnderscoreDash('cp'.$Code_Page_OldWest), 'cp'.$Code_Page_Western ); my %EncodingNames = ( 'cp'.$Code_Page_Central, 'Central European', 'cp'.$Code_Page_Western, 'Western European', 'cp'.$Code_Page_Turkish, ' Turkish ', 'cp'.$Code_Page_Baltic, ' Baltic ' ); my %NonAccenChars = ( #--------------------------------# 'cp'.$Code_Page_Central, # Central European (cp1250) # #--------------------------------# #€_‚_„…†‡_‰Š‹ŚŤŽŹ_‘’“”•–—_™š›śťžź# 'E_,_,.++_%S_STZZ_````.--_Ts_stzz'. # ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľż# '_``LoAlS`CS_--RZ`+,l`uP.,as_L~lz'. #ŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢß# 'RAAAALCCCEEEEIIDDNNOOOOxRUUUUYTS'. #ŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙# 'raaaalccceeeeiiddnnoooo%ruuuuyt`', #--------------------------------# 'cp'.$Code_Page_Western, # Western European (cp1252) # #--------------------------------# #€_‚ƒ„…†‡ˆ‰Š‹Œ_Ž__‘’“”•–—˜™š›œ_žŸ# 'E_,f,.++^%S_O_Z__````.--~Ts_o_zY'. # ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿# '_!cLoYlS`Ca_--R-`+23`uP.,10_qh3_'. #ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞß# 'AAAAAAACEEEEIIIIDNOOOOOxOUUUUYTS'. #àáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ# 'aaaaaaaceeeeiiiidnooooo%ouuuuyty', #--------------------------------# 'cp'.$Code_Page_Turkish, # Turkish (cp1254) # #--------------------------------# #€_‚ƒ„…†‡ˆ‰Š‹Œ____‘’“”•–—˜™š›œ__Ÿ# 'E_,f,.++^%S_O____````.--~Ts_o__Y'. # ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿# '_!cLoYlS`Ca_--R-`+23`uP.,10_qh3_'. #ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞß# 'AAAAAAACEEEEIIIIGNOOOOOxOUUUUISS'. #àáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ# 'aaaaaaaceeeeiiiignooooo%ouuuuisy', #--------------------------------# 'cp'.$Code_Page_Baltic, # Baltic (cp1257) # #--------------------------------# #€_‚_„…†‡_‰_‹_¨ˇ¸_‘’“”•–—_™_›_¯˛_# 'E_,_,.++_%___``,_````.--_T___-,_'. # �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æ# '__cLo_lSOCR_--RA`+23`uP.o1r_qh3a'. #ĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽß# 'AIACAAEECEZEGKILSNNOOOOxULSUUZZS'. #ąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙# 'aiacaaeecezegkilsnnoooo%ulsuuzz`' ); my %AccentedChars; my $AccentedChars = ''; my $NonAccenChars = ''; for ( $Code_Page_Central, $Code_Page_Western, $Code_Page_Turkish, $Code_Page_Baltic ) { $AccentedChars{'cp'.$_} = decode('cp'.$_, $HighBitSetChars); $AccentedChars .= $AccentedChars{'cp'.$_}; $NonAccenChars .= $NonAccenChars{'cp'.$_}; } #print "\n", length($NonAccenChars), ' ', $NonAccenChars,"\n"; #print "\n", length($AccentedChars), ' ', $AccentedChars,"\n"; my $QuotedMetaNonAccenChars = quotemeta($NonAccenChars); my $DiacriticalChars = ''; for ( 0x0300..0x036F, 0x1DC0..0x1DFF ) { $DiacriticalChars .= chr($_) } #----------------------------------------------------------------------------- # Parse options and parameters #----------------------------------------------------------------------------- my $b_Help = 0; my $b_Interactive = 1; my $b_UTF8 = 0; my $b_Parameter = 0; my $Folder; for ( @ARGV ) { if ( lc($_) eq '--' ) { $b_Parameter = 1 } elsif ( (not $b_Parameter) and (lc($_) eq '--batch') ) { $b_Interactive = 0 } elsif ( (not $b_Parameter) and (lc($_) eq '--utf8') ) { $b_UTF8 = 1 } elsif ( $b_Parameter or (substr($_, 0, 1) ne '-') ) { if ( defined($Folder) ) { die "$0 accepts only 1 parameter\n" } else { $Folder = $_ } } else { $b_Help = 1 } } #----------------------------------------------------------------------------- # Help #----------------------------------------------------------------------------- if ( $b_Help ) { die << "END_OF_HELP" $0 [--help] [--batch] [--] [folder] This script renames files with accented and diacritical Latin characters : - This PERL script starts from the folder given in parameter, or else from the current folder. - It recursively searches for files with characters belonging to 80 - FF of CP 1250, CP 1252, CP 1254 and CP 1257 (mostly accented Latin characters) or Latin characters having diacritical marks. - It calculates new file names by removing the accents and diacritical marks only from Latin characters (For example, Été --> Ete). - It displays all proposed renaming and perhaps conflicts, and asks the user for global approval. - If the user has approved, it renames all files having no conflict. Option '--batch' avoids interactive questions. Use with care. Option '--' avoids the next parameter to be interpreted as option. SPECIAL WARNING : - This script was originally encoded in UTF-8, and should stay so. - This script may rename a lot of files. - Files names are theoretically all encoded only with UTF-8. But some file names may be found to contain also some characters having legacy encoding. - The author has applied efforts for consistency checks, robustness, conflict detection and use of appropriate encoding. So this script should only rename files by removing accents and diacritical marks from Latin characters. - But this script has been tested only under a limited number of OS (Windows, Mac OS X, Linux) and a limited number of terminal encodings (CP 850, ISO-8859-1, UTF-8). - So, under weird circumstances, this script could rename many files with random names. - Therefore, this script should be used with care, and modified with extreme care (beware encoding of internal strings, inputs, outputs and commands) END_OF_HELP } #----------------------------------------------------------------------------- # If requested, change current folder #----------------------------------------------------------------------------- if ( defined($Folder) ) { chdir($Folder) or die "Can NOT set '$Folder' as current folder\n" } #----------------------------------------------------------------------------- # Following instruction is MANDATORY. # The return value should be non-zero, but on some systems it is zero. #----------------------------------------------------------------------------- utf8::decode($AccentedChars); # or die "$0: '\$AccentedChars' should be UTF-8 but is NOT.\n"; #----------------------------------------------------------------------------- # Check consistency on 'tr' #----------------------------------------------------------------------------- $_ = $AccentedChars; eval "tr/$AccentedChars/$QuotedMetaNonAccenChars/"; if ( $@ ) { warn $@ } if ( $@ or ($_ ne $NonAccenChars) ) { die "$0: Consistency check on 'tr' FAILED :\n\n", "Translated Accented Chars : ", length($_), ' : ', $_, "\n\n", " Non Accented Chars : ", length($NonAccenChars), ' : ', $NonAccenChars, "\n" } #----------------------------------------------------------------------------- # Constants depending on the OS #----------------------------------------------------------------------------- my $b_Windows = ( defined($ENV{'OS'}) and ($ENV{'OS'} eq 'Windows_NT') ); my ($Q, $sep, $sep2, $HOME, $Find, @List, $cwd, @Move); if ( $b_Windows ) { $Q = '"'; $sep = '\\'; $sep2 = '\\\\'; $HOME = $ENV{'USERPROFILE'}; $Find = 'dir /b /s'; @List = ( ( (`ver 2>&1` =~ m/version\s+([0-9]+)/i) and ($1 >= 6) ) ? ('icacls') : ( 'cacls') ); $cwd = `cd`; chomp $cwd; $cwd = quotemeta($cwd); @Move = ('move'); } else { $Q = "'"; $sep = '/'; $sep2 = '/'; $HOME = $ENV{'HOME'}; $Find = 'find .'; @List = ('ls', '-d', '--'); @Move = ('mv', '--'); if ( -w '/bin' ) { die "$0: For safety reasons, ", "usage is BLOCKED to administrators.\n"} } my $Encoding; my $ucEncoding; my $InputPipe = '-|'; # Used as global variable #----------------------------------------------------------------------------- # Under Windows, associate input and output encodings to code pages : # - Get the original code page, # - If it is not UTF-8, try to set it to UTF-8, # - Define the input encoding as the one associated to the ACTIVE code page, # - If STDOUT is the console, encode output for the ORIGINAL code page. #----------------------------------------------------------------------------- my $Code_Page_Original; my $Code_Page_Active; if ( $b_Windows ) { #----------------------------------------------------------------------- # Get the original code page #----------------------------------------------------------------------- $_ = `chcp`; m/([0-9]+)$/ or die "Non numeric Windows code page : ", $_; $Code_Page_Original = $1; print 'Windows Original Code Page = ', $Code_Page_Original, ( $Code_Page_Original == $Code_Page_UTF8 ? ' = UTF-8, display is perhaps correct with a true type font.' : '' ), "\n\n"; $Code_Page_Active = $Code_Page_Original ; #----------------------------------------------------------------------- # The input encoding must be the same as the ACTIVE code page #----------------------------------------------------------------------- $Encoding = ( $Code_Page_Active == $Code_Page_UTF8 ? 'utf8' : 'cp'.$Code_Page_Active ) ; $InputPipe .= ":encoding($Encoding)"; print "InputPipe = '$InputPipe'\n\n"; #----------------------------------------------------------------------- # If STDOUT is the console, output encoding must be the same as the # ORIGINAL code page #----------------------------------------------------------------------- if ( $Code_Page_Original != $Code_Page_UTF8 ) { no warnings 'unopened'; @_ = stat(STDOUT); use warnings; if ( scalar(@_) and ($_[0] == 1) ) { binmode(STDOUT, ":encoding(cp$Code_Page_Original)") } else { binmode(STDOUT, ":encoding($Encoding)") } } } #----------------------------------------------------------------------------- # Under *nix, if the 'LANG' environment variable contains an encoding, # verify that this encoding is supported by the OS and by PERL. #----------------------------------------------------------------------------- elsif ( defined($ENV{'LANG'}) and ($ENV{'LANG'} =~ m/\.([^\@]+)$/i) ) { $Encoding = $1; my $Kernel = `uname -s`; chomp $Kernel; my $ucEncoding = &ucRemoveEolUnderscoreDash($Encoding); if ( (lc($Kernel) ne 'darwin') and not grep {$_ eq $ucEncoding} ( map { ($_, &ucRemoveEolUnderscoreDash($_)) } `locale -m` ) ) { die "Encoding = '$Encoding' or '$ucEncoding' NOT supported ". "by the OS\n" } my $ucLocale = &ucRemoveEolUnderscoreDash($ENV{'LANG'}); if ( not grep {$_ eq $ucLocale} ( map { ($_, &ucRemoveEolUnderscoreDash($_)) } `locale -a` ) ) { die "Locale = '$ENV{LANG}' or '$ucLocale' NOT supported ". "by the OS\n" } if ( not defined(Encode::find_encoding($Encoding)) ) { die "Encoding = '$Encoding' or '$ucEncoding' NOT supported ". "by PERL\n" } print "Encoding = '$Encoding' is supported by the OS and PERL\n\n"; binmode(STDOUT, ":encoding($Encoding)"); } #----------------------------------------------------------------------------- # Check consistency between parameter of 'echo' and output of 'echo' #----------------------------------------------------------------------------- undef $_; if ( defined($Encoding) ) { $ucEncoding = &ucRemoveEolUnderscoreDash($Encoding); if ( defined($SuperEncodings{$ucEncoding}) ) { $_ = substr($AccentedChars{$SuperEncodings{$ucEncoding}}, 0x20, 0x60) } elsif ( defined($AccentedChars{$Encoding}) ) { $_ = $AccentedChars{$Encoding} } elsif ( $Encoding =~ m/^utf-?8$/i ) { $_ = $AccentedChars } } if ( not defined($_) ) # Chosen chars are same in 4 code pages { $_ = decode('cp'.$Code_Page_Central, pack('C*', 0xC9, 0xD3, 0xD7, 0xDC, # ÉÓ×Ü 0xE9, 0xF3, 0xF7, 0xFC)) } # éó÷ü #print $_, " (Parameter)\n\n"; #system 'echo', $_; utf8::decode($_); #print "\n", $_, " (Parameter after utf8::decode)\n\n"; my @EchoCommand = ( $b_Windows ? "echo $_" : ('echo', $_) ); #system @EchoCommand; open(ECHO, $InputPipe, @EchoCommand) or die 'echo $_: ', $!; my $Output = join('', <ECHO>); close(ECHO); chomp $Output; #print "\n", $Output, " (Output of 'echo')\n"; utf8::decode($Output); #print "\n", $Output, " (Output of 'echo' after utf8::decode)\n\n"; if ( $Output ne $_ ) { warn "$0: Consistency check between parameter ", "of 'echo' and output of 'echo' FAILED :\n\n", "Parameter of 'echo' : ", length($_), ' : ', $_, "\n\n", " Output of 'echo' : ", length($Output), ' : ', $Output, "\n"; exit 1; } #----------------------------------------------------------------------------- # Print the translation table #----------------------------------------------------------------------------- if ( defined($Encoding) ) { undef $_; $ucEncoding = &ucRemoveEolUnderscoreDash($Encoding); if ( defined($SuperEncodings{$ucEncoding}) ) { $_ = $SuperEncodings{$ucEncoding}; print "--------- $EncodingNames{$_} ---------\n", ' ', substr($AccentedChars{$_}, 0x20, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x20, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x40, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x40, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x60, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x60, 0x20), "\n\n" } else { for ( 'cp'.$Code_Page_Central, 'cp'.$Code_Page_Western, 'cp'.$Code_Page_Turkish, 'cp'.$Code_Page_Baltic ) { if ( ('cp'.$Encoding eq $_) or ($Encoding =~ m/^utf-?8$/i) ) { print "--------- $EncodingNames{$_} ---------\n", ' ', substr($AccentedChars{$_}, 0, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x20, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x20, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x40, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x40, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x60, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x60, 0x20), "\n\n" } } } } #----------------------------------------------------------------------------- # Completely optional : # Inside the Unison file, find the accented file names to ignore #----------------------------------------------------------------------------- my $UnisonFile = $HOME.$sep.'.unison'.$sep.'common.unison'; my @Ignores; if ( open(UnisonFile, '<', $UnisonFile) ) { print "\nUnison File '", $UnisonFile, "'\n"; while ( <UnisonFile> ) { if ( m/^\s*ignore\s*=\s*Name\s*(.+)/ ) { $_ = $1 ; if ( m/[$AccentedChars]/ ) { push(@Ignores, $_) } } } close(UnisonFile); } print map(" Ignore: ".$_."\n", @Ignores); #----------------------------------------------------------------------------- # Function OutputAndErrorFromCommand : # # Execute the command given as array in parameter, and return STDOUT + STDERR # # Reads global variable $InputPipe #----------------------------------------------------------------------------- sub OutputAndErrorFromCommand { local $_; my @Command = @_; # Protects content of @_ from any modification #--------------------------------------------------------------------------- # Under Windows, fork fails, so : # - Enclose into double quotes parameters containing blanks or simple # quotes, # - Use piped open with redirection of STDERR. #--------------------------------------------------------------------------- if ( defined($ENV{'OS'}) and ($ENV{'OS'} eq 'Windows_NT') ) { for ( @Command ) { s/^((-|.*(\s|')).*)$/$Q$1$Q/ } my $Command = join(' ', @Command); #print "\n", $Command; open(COMMAND, $InputPipe, "$Command 2>&1") or die '$Command: ', $!; } #--------------------------------------------------------------------------- # Under Unix, quoting is too difficult, but fork succeeds #--------------------------------------------------------------------------- else { my $pid = open(COMMAND, $InputPipe); defined($pid) or die "Can't fork: $!"; if ( $pid == 0 ) # Child process { open STDERR, '>&=STDOUT'; exec @Command; # Returns only on failure die "Can't @Command"; } } $_ = join('', <COMMAND>); # Child's STDOUT + STDERR close COMMAND; chomp; utf8::decode($_); $_; } #----------------------------------------------------------------------------- # Find recursively all files inside the current folder. # Verify accessibility of files with accented names. # Calculate non-accented file names from accented file names. # Build the list of duplicates. #----------------------------------------------------------------------------- my %Olds; # $Olds{$New} = [ $Old1, $Old2, ... ] my $Old; my $Dir; my $Command; my $ErrorMessage; my $New; my %News; print "\n\nFiles with accented name and the corresponding non-accented name ", ":\n"; open(FIND, $InputPipe, $Find) or die $Find, ': ', $!; FILE: while ( <FIND> ) { chomp; #--------------------------------------------------------------------------- # If the file path contains UTF-8, following instruction is MANDATORY. # If the file path does NOT contain UTF-8, it should NOT hurt. #--------------------------------------------------------------------------- utf8::decode($_); if ( $b_Windows ) { s/^$cwd$sep2// } else { s/^\.$sep2// } #--------------------------------------------------------------------------- # From now on : $_ = Dir/OldFilename #--------------------------------------------------------------------------- push(@{$Olds{$_}}, $_); if ( m/([^$sep2]+)$/ and ($1 =~ m/[$AccentedChars]|([\ -\~][$DiacriticalChars])/) ) { if ( $b_Windows and m/$Q/ ) { print "\n $Q$_$Q\n*** contains quotes.\n"; next; } for my $Ignore ( @Ignores ) { if ( m/$Ignore$/ ) { next FILE } } $Old = $_ ; m/^(.*$sep2)?([^$sep2]+)$/; $Dir = ( defined($1) ? $1 : ''); $_ = $2; #--------------------------------------------------------------------- # From now on : $Old = Dir/OldFilename # $_ = OldFilename #--------------------------------------------------------------------- print "\n $Q$Old$Q\n"; $ErrorMessage = &OutputAndErrorFromCommand(@List, $Old); if ( $? != 0 ) { print "*** $ErrorMessage\n" } else { #--------------------------------------------------------------- # Change accented Latin chars to non-accented chars. # Remove all diacritical marks after Latin chars. #--------------------------------------------------------------- eval "tr/$AccentedChars/$QuotedMetaNonAccenChars/"; s/([\ -\~])[$DiacriticalChars]+/$1/g; #--------------------------------------------------------------- # From now on : $Old = Dir/OldFilename # $_ = NewFilename #--------------------------------------------------------------- if ( $@ ) { warn $@ } else { $New = $Dir.$_; if ( $b_Windows or (not utf8::is_utf8($Dir)) ) # Weird { utf8::decode($New) } # but necessary $News{$Old} = $New; push(@{$Olds{$New}}, $Old); } print "--> $Q$Dir$_$Q\n"; } } } close(FIND); #----------------------------------------------------------------------------- # Print list of duplicate non-accented file names #----------------------------------------------------------------------------- my $b_NoDuplicate = 1; for my $New ( sort keys %Olds ) { if ( scalar(@{$Olds{$New}}) > 1 ) { if ( $b_NoDuplicate ) { print "\n\nFollowing files would have same non-accented name ", ":\n"; $b_NoDuplicate = 0; } print "\n", map(' '.$_."\n", @{$Olds{$New}}), '--> ', $New, "\n"; for ( @{$Olds{$New}} ) { delete $News{$_} }; } } #----------------------------------------------------------------------------- # If there are NO file to rename, then exit #----------------------------------------------------------------------------- my $Number = scalar(keys %News); print "\n\n"; if ( $Number < 1 ) { print "There are NO file to rename\n"; exit; } #----------------------------------------------------------------------------- # Ask the user for global approval of renaming #----------------------------------------------------------------------------- if ( $b_Interactive ) { print "In order to really rename the ", $Number, " files which can safely be renamed, type 'rename' : "; $_ = <STDIN>; sleep 1; # Gives time to PERL to handle interrupts if ( not m/^rename$/i ) { exit 1 } } else { print $Number, " files will be renamed\n\n" } #----------------------------------------------------------------------------- # Rename accented file names sorted descending by name size #----------------------------------------------------------------------------- $Number = 0; my $Move = join(' ', @Move); for ( sort {length($b) <=> length($a)} keys %News ) { $ErrorMessage = &OutputAndErrorFromCommand(@Move, $_, $News{$_}); if ( $? == 0 ) { $Number++ } else { print "\n$Move $Q$_$Q\n", (' ' x length($Move)), " $Q$News{$_}$Q\n", ('*' x length($Move)), " $ErrorMessage\n" } } print "\n$Number files have been successfully renamed\n"; __END__ ```
261,515
I have a large set of files, some of which contain special characters in the filename (e.g. ä,ö,%, and others). I'd like a script file to iterate over these files and rename them removing the special characters. I don't really mind what it does, but it could replace them with underscores for example e.g. Störung%20.doc would be renamed to St\_rung\_20.doc In order of preference: 1. A Windiws batch file 2. A Windows script file to run with cscript (vbs) 3. A third party piece of software that can be run from the command-line (i.e. no user interaction required) 4. Another language script file, for which I'd have to install an additional script engine Background: I'm trying to encrypt these file with GnuPG on Windows but it doesn't seem to handle special characters in filenames with the --encrypt-files option.
2008/11/04
[ "https://Stackoverflow.com/questions/261515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9625/" ]
Thanks to Tomalak who actually pointed me in the right direction. Thought I'd post here for completeness. The problem seems to be that the codepage used by GPG is fixed (Latin I) independent of the codepage configured in the console. But once he pointed this out, I figured out how to workaraound this. The trick is to change the codepage before generating the file list. This will actually make the filelist appear to be incorrect when viewed in the console. However, when passed to GPG, it works fine. GPG accepts the files and spits out the encrytped files with correct filenames. The batch file looks something like this: ``` chcp 1252 dir /b /s /a-d MyFolder >filelist.txt gpg -r [email protected] --encrypt-files <filelist.txt ```
I'm using this batch to rename folders and seems to work fine so far... In my case codepage is 1252, yours might be different. ``` mode con codepage select=1252 @echo off Setlocal enabledelayedexpansion ::folder only (/D option) for /R /D %%d in (*) do ( set an=%%~nd set bn=!an:.=_! set cn=!bn:-=_! set dn=!cn: =_! set en=!dn:Á=A! set fn=!en:É=E! set gn=!fn:Í=I! set hn=!gn:Ó=O! set in=!hn:Ú=U! set jn=!in:Ü=U! set kn=!jn:á=a! set ln=!kn:é=e! set mn=!ln:í=i! set nn=!mn:ó=o! set on=!nn:ú=u! set pn=!on:ü=u! set qn=!pn:Ñ=N! set zn=!on:ñ=n! set ax=%%~xd set bx=!ax:.=_! set cx=!bx:-=_! set dx=!cx: =_! set bx=!ax:.=_! set cx=!bx:-=_! set dx=!cx: =_! set ex=!dx:Á=A! set fx=!ex:É=E! set gx=!fx:Í=I! set hx=!gx:Ó=O! set ix=!hx:Ú=U! set jx=!ix:Ü=U! set kx=!jx:á=a! set lx=!kx:é=e! set mx=!lx:í=i! set nx=!mx:ó=o! set ox=!nx:ú=u! set px=!ox:ü=u! set qx=!px:Ñ=N! set zx=!ox:ñ=n! if [!an!]==[] (set zn=) if [!ax!]==[] (set zx=) set newname=!zn!!zx! if /i not [%%~nd%%~xd]==[!newname!] rename "%%d" !newname! ) endlocal pause ```
261,515
I have a large set of files, some of which contain special characters in the filename (e.g. ä,ö,%, and others). I'd like a script file to iterate over these files and rename them removing the special characters. I don't really mind what it does, but it could replace them with underscores for example e.g. Störung%20.doc would be renamed to St\_rung\_20.doc In order of preference: 1. A Windiws batch file 2. A Windows script file to run with cscript (vbs) 3. A third party piece of software that can be run from the command-line (i.e. no user interaction required) 4. Another language script file, for which I'd have to install an additional script engine Background: I'm trying to encrypt these file with GnuPG on Windows but it doesn't seem to handle special characters in filenames with the --encrypt-files option.
2008/11/04
[ "https://Stackoverflow.com/questions/261515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9625/" ]
Following 'RenameFilesWithAccentedAndDiacriticalLatinChars.pl' PERL script renames files with accented and diacritical Latin characters : * This PERL script starts from the folder given in parameter, or else from the current folder. * It recursively searches for files with characters belonging to 80 - FF of CP 1250, CP 1252, CP 1254 and CP 1257 (mostly accented Latin characters) or Latin characters having diacritical marks. * It calculates new file names by removing the accents and diacritical marks only from Latin characters (For example, Été --> Ete). * It displays all proposed renaming and perhaps conflicts, and asks the user for global approval. * If the user has approved, it renames all files having no conflict. Option '--batch' avoids interactive questions. Use with care. Option '--' avoids the next parameter to be interpreted as option. **Special Warning** : * This script was originally encoded in UTF-8, and should stay so. * This script may rename a lot of files. * Files names are theoretically all encoded only with UTF-8. But some file names may be found to contain also some characters having legacy encoding. * The author has applied efforts for consistency checks, robustness, conflict detection and use of appropriate encoding. So this script should only rename files by removing accents and diacritical marks from Latin characters. * But this script has been tested only under a limited number of OS (Windows, Mac OS X, Linux) and a limited number of terminal encodings (CP 850, ISO-8859-1, UTF-8). * So, under weird circumstances, this script could rename many files with random names. * Therefore, this script should be used with care, and modified with extreme care (beware encoding of internal strings, inputs, outputs and commands) ``` #!/usr/bin/perl -w #============================================================================= # # Copyright 2010 Etienne URBAH # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details at # http://www.gnu.org/licenses/gpl.html # # For usage and SPECIAL WARNING, see the 'Help' section below. # #============================================================================= use 5.008_000; # For correct Unicode support use warnings; use strict; use Encode; $| = 1; # Autoflush STDOUT #----------------------------------------------------------------------------- # Function ucRemoveEolUnderscoreDash : # Set Uppercase, remove End of line, Underscores and Dashes #----------------------------------------------------------------------------- sub ucRemoveEolUnderscoreDash { local $_ = uc($_[0]); chomp; tr/_\-//d; $_; } #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- my $Encoding_Western = 'ISO-8859-1'; my $Encoding_Central = 'ISO-8859-2'; my $Encoding_Baltic = 'ISO-8859-4'; my $Encoding_Turkish = 'ISO-8859-9'; my $Encoding_W_Euro = 'ISO-8859-15'; my $Code_Page_OldWest = 850; my $Code_Page_Central = 1250; my $Code_Page_Western = 1252; my $Code_Page_Turkish = 1254; my $Code_Page_Baltic = 1257; my $Code_Page_UTF8 = 65001; my $HighBitSetChars = pack('C*', 0x80..0xFF); my %SuperEncodings = ( &ucRemoveEolUnderscoreDash($Encoding_Western), 'cp'.$Code_Page_Western, &ucRemoveEolUnderscoreDash($Encoding_Central), 'cp'.$Code_Page_Central, &ucRemoveEolUnderscoreDash($Encoding_Baltic), 'cp'.$Code_Page_Baltic, &ucRemoveEolUnderscoreDash($Encoding_Turkish), 'cp'.$Code_Page_Turkish, &ucRemoveEolUnderscoreDash($Encoding_W_Euro), 'cp'.$Code_Page_Western, &ucRemoveEolUnderscoreDash('cp'.$Code_Page_OldWest), 'cp'.$Code_Page_Western ); my %EncodingNames = ( 'cp'.$Code_Page_Central, 'Central European', 'cp'.$Code_Page_Western, 'Western European', 'cp'.$Code_Page_Turkish, ' Turkish ', 'cp'.$Code_Page_Baltic, ' Baltic ' ); my %NonAccenChars = ( #--------------------------------# 'cp'.$Code_Page_Central, # Central European (cp1250) # #--------------------------------# #€_‚_„…†‡_‰Š‹ŚŤŽŹ_‘’“”•–—_™š›śťžź# 'E_,_,.++_%S_STZZ_````.--_Ts_stzz'. # ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľż# '_``LoAlS`CS_--RZ`+,l`uP.,as_L~lz'. #ŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢß# 'RAAAALCCCEEEEIIDDNNOOOOxRUUUUYTS'. #ŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙# 'raaaalccceeeeiiddnnoooo%ruuuuyt`', #--------------------------------# 'cp'.$Code_Page_Western, # Western European (cp1252) # #--------------------------------# #€_‚ƒ„…†‡ˆ‰Š‹Œ_Ž__‘’“”•–—˜™š›œ_žŸ# 'E_,f,.++^%S_O_Z__````.--~Ts_o_zY'. # ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿# '_!cLoYlS`Ca_--R-`+23`uP.,10_qh3_'. #ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞß# 'AAAAAAACEEEEIIIIDNOOOOOxOUUUUYTS'. #àáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ# 'aaaaaaaceeeeiiiidnooooo%ouuuuyty', #--------------------------------# 'cp'.$Code_Page_Turkish, # Turkish (cp1254) # #--------------------------------# #€_‚ƒ„…†‡ˆ‰Š‹Œ____‘’“”•–—˜™š›œ__Ÿ# 'E_,f,.++^%S_O____````.--~Ts_o__Y'. # ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿# '_!cLoYlS`Ca_--R-`+23`uP.,10_qh3_'. #ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞß# 'AAAAAAACEEEEIIIIGNOOOOOxOUUUUISS'. #àáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ# 'aaaaaaaceeeeiiiignooooo%ouuuuisy', #--------------------------------# 'cp'.$Code_Page_Baltic, # Baltic (cp1257) # #--------------------------------# #€_‚_„…†‡_‰_‹_¨ˇ¸_‘’“”•–—_™_›_¯˛_# 'E_,_,.++_%___``,_````.--_T___-,_'. # �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æ# '__cLo_lSOCR_--RA`+23`uP.o1r_qh3a'. #ĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽß# 'AIACAAEECEZEGKILSNNOOOOxULSUUZZS'. #ąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙# 'aiacaaeecezegkilsnnoooo%ulsuuzz`' ); my %AccentedChars; my $AccentedChars = ''; my $NonAccenChars = ''; for ( $Code_Page_Central, $Code_Page_Western, $Code_Page_Turkish, $Code_Page_Baltic ) { $AccentedChars{'cp'.$_} = decode('cp'.$_, $HighBitSetChars); $AccentedChars .= $AccentedChars{'cp'.$_}; $NonAccenChars .= $NonAccenChars{'cp'.$_}; } #print "\n", length($NonAccenChars), ' ', $NonAccenChars,"\n"; #print "\n", length($AccentedChars), ' ', $AccentedChars,"\n"; my $QuotedMetaNonAccenChars = quotemeta($NonAccenChars); my $DiacriticalChars = ''; for ( 0x0300..0x036F, 0x1DC0..0x1DFF ) { $DiacriticalChars .= chr($_) } #----------------------------------------------------------------------------- # Parse options and parameters #----------------------------------------------------------------------------- my $b_Help = 0; my $b_Interactive = 1; my $b_UTF8 = 0; my $b_Parameter = 0; my $Folder; for ( @ARGV ) { if ( lc($_) eq '--' ) { $b_Parameter = 1 } elsif ( (not $b_Parameter) and (lc($_) eq '--batch') ) { $b_Interactive = 0 } elsif ( (not $b_Parameter) and (lc($_) eq '--utf8') ) { $b_UTF8 = 1 } elsif ( $b_Parameter or (substr($_, 0, 1) ne '-') ) { if ( defined($Folder) ) { die "$0 accepts only 1 parameter\n" } else { $Folder = $_ } } else { $b_Help = 1 } } #----------------------------------------------------------------------------- # Help #----------------------------------------------------------------------------- if ( $b_Help ) { die << "END_OF_HELP" $0 [--help] [--batch] [--] [folder] This script renames files with accented and diacritical Latin characters : - This PERL script starts from the folder given in parameter, or else from the current folder. - It recursively searches for files with characters belonging to 80 - FF of CP 1250, CP 1252, CP 1254 and CP 1257 (mostly accented Latin characters) or Latin characters having diacritical marks. - It calculates new file names by removing the accents and diacritical marks only from Latin characters (For example, Été --> Ete). - It displays all proposed renaming and perhaps conflicts, and asks the user for global approval. - If the user has approved, it renames all files having no conflict. Option '--batch' avoids interactive questions. Use with care. Option '--' avoids the next parameter to be interpreted as option. SPECIAL WARNING : - This script was originally encoded in UTF-8, and should stay so. - This script may rename a lot of files. - Files names are theoretically all encoded only with UTF-8. But some file names may be found to contain also some characters having legacy encoding. - The author has applied efforts for consistency checks, robustness, conflict detection and use of appropriate encoding. So this script should only rename files by removing accents and diacritical marks from Latin characters. - But this script has been tested only under a limited number of OS (Windows, Mac OS X, Linux) and a limited number of terminal encodings (CP 850, ISO-8859-1, UTF-8). - So, under weird circumstances, this script could rename many files with random names. - Therefore, this script should be used with care, and modified with extreme care (beware encoding of internal strings, inputs, outputs and commands) END_OF_HELP } #----------------------------------------------------------------------------- # If requested, change current folder #----------------------------------------------------------------------------- if ( defined($Folder) ) { chdir($Folder) or die "Can NOT set '$Folder' as current folder\n" } #----------------------------------------------------------------------------- # Following instruction is MANDATORY. # The return value should be non-zero, but on some systems it is zero. #----------------------------------------------------------------------------- utf8::decode($AccentedChars); # or die "$0: '\$AccentedChars' should be UTF-8 but is NOT.\n"; #----------------------------------------------------------------------------- # Check consistency on 'tr' #----------------------------------------------------------------------------- $_ = $AccentedChars; eval "tr/$AccentedChars/$QuotedMetaNonAccenChars/"; if ( $@ ) { warn $@ } if ( $@ or ($_ ne $NonAccenChars) ) { die "$0: Consistency check on 'tr' FAILED :\n\n", "Translated Accented Chars : ", length($_), ' : ', $_, "\n\n", " Non Accented Chars : ", length($NonAccenChars), ' : ', $NonAccenChars, "\n" } #----------------------------------------------------------------------------- # Constants depending on the OS #----------------------------------------------------------------------------- my $b_Windows = ( defined($ENV{'OS'}) and ($ENV{'OS'} eq 'Windows_NT') ); my ($Q, $sep, $sep2, $HOME, $Find, @List, $cwd, @Move); if ( $b_Windows ) { $Q = '"'; $sep = '\\'; $sep2 = '\\\\'; $HOME = $ENV{'USERPROFILE'}; $Find = 'dir /b /s'; @List = ( ( (`ver 2>&1` =~ m/version\s+([0-9]+)/i) and ($1 >= 6) ) ? ('icacls') : ( 'cacls') ); $cwd = `cd`; chomp $cwd; $cwd = quotemeta($cwd); @Move = ('move'); } else { $Q = "'"; $sep = '/'; $sep2 = '/'; $HOME = $ENV{'HOME'}; $Find = 'find .'; @List = ('ls', '-d', '--'); @Move = ('mv', '--'); if ( -w '/bin' ) { die "$0: For safety reasons, ", "usage is BLOCKED to administrators.\n"} } my $Encoding; my $ucEncoding; my $InputPipe = '-|'; # Used as global variable #----------------------------------------------------------------------------- # Under Windows, associate input and output encodings to code pages : # - Get the original code page, # - If it is not UTF-8, try to set it to UTF-8, # - Define the input encoding as the one associated to the ACTIVE code page, # - If STDOUT is the console, encode output for the ORIGINAL code page. #----------------------------------------------------------------------------- my $Code_Page_Original; my $Code_Page_Active; if ( $b_Windows ) { #----------------------------------------------------------------------- # Get the original code page #----------------------------------------------------------------------- $_ = `chcp`; m/([0-9]+)$/ or die "Non numeric Windows code page : ", $_; $Code_Page_Original = $1; print 'Windows Original Code Page = ', $Code_Page_Original, ( $Code_Page_Original == $Code_Page_UTF8 ? ' = UTF-8, display is perhaps correct with a true type font.' : '' ), "\n\n"; $Code_Page_Active = $Code_Page_Original ; #----------------------------------------------------------------------- # The input encoding must be the same as the ACTIVE code page #----------------------------------------------------------------------- $Encoding = ( $Code_Page_Active == $Code_Page_UTF8 ? 'utf8' : 'cp'.$Code_Page_Active ) ; $InputPipe .= ":encoding($Encoding)"; print "InputPipe = '$InputPipe'\n\n"; #----------------------------------------------------------------------- # If STDOUT is the console, output encoding must be the same as the # ORIGINAL code page #----------------------------------------------------------------------- if ( $Code_Page_Original != $Code_Page_UTF8 ) { no warnings 'unopened'; @_ = stat(STDOUT); use warnings; if ( scalar(@_) and ($_[0] == 1) ) { binmode(STDOUT, ":encoding(cp$Code_Page_Original)") } else { binmode(STDOUT, ":encoding($Encoding)") } } } #----------------------------------------------------------------------------- # Under *nix, if the 'LANG' environment variable contains an encoding, # verify that this encoding is supported by the OS and by PERL. #----------------------------------------------------------------------------- elsif ( defined($ENV{'LANG'}) and ($ENV{'LANG'} =~ m/\.([^\@]+)$/i) ) { $Encoding = $1; my $Kernel = `uname -s`; chomp $Kernel; my $ucEncoding = &ucRemoveEolUnderscoreDash($Encoding); if ( (lc($Kernel) ne 'darwin') and not grep {$_ eq $ucEncoding} ( map { ($_, &ucRemoveEolUnderscoreDash($_)) } `locale -m` ) ) { die "Encoding = '$Encoding' or '$ucEncoding' NOT supported ". "by the OS\n" } my $ucLocale = &ucRemoveEolUnderscoreDash($ENV{'LANG'}); if ( not grep {$_ eq $ucLocale} ( map { ($_, &ucRemoveEolUnderscoreDash($_)) } `locale -a` ) ) { die "Locale = '$ENV{LANG}' or '$ucLocale' NOT supported ". "by the OS\n" } if ( not defined(Encode::find_encoding($Encoding)) ) { die "Encoding = '$Encoding' or '$ucEncoding' NOT supported ". "by PERL\n" } print "Encoding = '$Encoding' is supported by the OS and PERL\n\n"; binmode(STDOUT, ":encoding($Encoding)"); } #----------------------------------------------------------------------------- # Check consistency between parameter of 'echo' and output of 'echo' #----------------------------------------------------------------------------- undef $_; if ( defined($Encoding) ) { $ucEncoding = &ucRemoveEolUnderscoreDash($Encoding); if ( defined($SuperEncodings{$ucEncoding}) ) { $_ = substr($AccentedChars{$SuperEncodings{$ucEncoding}}, 0x20, 0x60) } elsif ( defined($AccentedChars{$Encoding}) ) { $_ = $AccentedChars{$Encoding} } elsif ( $Encoding =~ m/^utf-?8$/i ) { $_ = $AccentedChars } } if ( not defined($_) ) # Chosen chars are same in 4 code pages { $_ = decode('cp'.$Code_Page_Central, pack('C*', 0xC9, 0xD3, 0xD7, 0xDC, # ÉÓ×Ü 0xE9, 0xF3, 0xF7, 0xFC)) } # éó÷ü #print $_, " (Parameter)\n\n"; #system 'echo', $_; utf8::decode($_); #print "\n", $_, " (Parameter after utf8::decode)\n\n"; my @EchoCommand = ( $b_Windows ? "echo $_" : ('echo', $_) ); #system @EchoCommand; open(ECHO, $InputPipe, @EchoCommand) or die 'echo $_: ', $!; my $Output = join('', <ECHO>); close(ECHO); chomp $Output; #print "\n", $Output, " (Output of 'echo')\n"; utf8::decode($Output); #print "\n", $Output, " (Output of 'echo' after utf8::decode)\n\n"; if ( $Output ne $_ ) { warn "$0: Consistency check between parameter ", "of 'echo' and output of 'echo' FAILED :\n\n", "Parameter of 'echo' : ", length($_), ' : ', $_, "\n\n", " Output of 'echo' : ", length($Output), ' : ', $Output, "\n"; exit 1; } #----------------------------------------------------------------------------- # Print the translation table #----------------------------------------------------------------------------- if ( defined($Encoding) ) { undef $_; $ucEncoding = &ucRemoveEolUnderscoreDash($Encoding); if ( defined($SuperEncodings{$ucEncoding}) ) { $_ = $SuperEncodings{$ucEncoding}; print "--------- $EncodingNames{$_} ---------\n", ' ', substr($AccentedChars{$_}, 0x20, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x20, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x40, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x40, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x60, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x60, 0x20), "\n\n" } else { for ( 'cp'.$Code_Page_Central, 'cp'.$Code_Page_Western, 'cp'.$Code_Page_Turkish, 'cp'.$Code_Page_Baltic ) { if ( ('cp'.$Encoding eq $_) or ($Encoding =~ m/^utf-?8$/i) ) { print "--------- $EncodingNames{$_} ---------\n", ' ', substr($AccentedChars{$_}, 0, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x20, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x20, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x40, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x40, 0x20), "\n\n", ' ', substr($AccentedChars{$_}, 0x60, 0x20), "\n", '--> ', substr($NonAccenChars{$_}, 0x60, 0x20), "\n\n" } } } } #----------------------------------------------------------------------------- # Completely optional : # Inside the Unison file, find the accented file names to ignore #----------------------------------------------------------------------------- my $UnisonFile = $HOME.$sep.'.unison'.$sep.'common.unison'; my @Ignores; if ( open(UnisonFile, '<', $UnisonFile) ) { print "\nUnison File '", $UnisonFile, "'\n"; while ( <UnisonFile> ) { if ( m/^\s*ignore\s*=\s*Name\s*(.+)/ ) { $_ = $1 ; if ( m/[$AccentedChars]/ ) { push(@Ignores, $_) } } } close(UnisonFile); } print map(" Ignore: ".$_."\n", @Ignores); #----------------------------------------------------------------------------- # Function OutputAndErrorFromCommand : # # Execute the command given as array in parameter, and return STDOUT + STDERR # # Reads global variable $InputPipe #----------------------------------------------------------------------------- sub OutputAndErrorFromCommand { local $_; my @Command = @_; # Protects content of @_ from any modification #--------------------------------------------------------------------------- # Under Windows, fork fails, so : # - Enclose into double quotes parameters containing blanks or simple # quotes, # - Use piped open with redirection of STDERR. #--------------------------------------------------------------------------- if ( defined($ENV{'OS'}) and ($ENV{'OS'} eq 'Windows_NT') ) { for ( @Command ) { s/^((-|.*(\s|')).*)$/$Q$1$Q/ } my $Command = join(' ', @Command); #print "\n", $Command; open(COMMAND, $InputPipe, "$Command 2>&1") or die '$Command: ', $!; } #--------------------------------------------------------------------------- # Under Unix, quoting is too difficult, but fork succeeds #--------------------------------------------------------------------------- else { my $pid = open(COMMAND, $InputPipe); defined($pid) or die "Can't fork: $!"; if ( $pid == 0 ) # Child process { open STDERR, '>&=STDOUT'; exec @Command; # Returns only on failure die "Can't @Command"; } } $_ = join('', <COMMAND>); # Child's STDOUT + STDERR close COMMAND; chomp; utf8::decode($_); $_; } #----------------------------------------------------------------------------- # Find recursively all files inside the current folder. # Verify accessibility of files with accented names. # Calculate non-accented file names from accented file names. # Build the list of duplicates. #----------------------------------------------------------------------------- my %Olds; # $Olds{$New} = [ $Old1, $Old2, ... ] my $Old; my $Dir; my $Command; my $ErrorMessage; my $New; my %News; print "\n\nFiles with accented name and the corresponding non-accented name ", ":\n"; open(FIND, $InputPipe, $Find) or die $Find, ': ', $!; FILE: while ( <FIND> ) { chomp; #--------------------------------------------------------------------------- # If the file path contains UTF-8, following instruction is MANDATORY. # If the file path does NOT contain UTF-8, it should NOT hurt. #--------------------------------------------------------------------------- utf8::decode($_); if ( $b_Windows ) { s/^$cwd$sep2// } else { s/^\.$sep2// } #--------------------------------------------------------------------------- # From now on : $_ = Dir/OldFilename #--------------------------------------------------------------------------- push(@{$Olds{$_}}, $_); if ( m/([^$sep2]+)$/ and ($1 =~ m/[$AccentedChars]|([\ -\~][$DiacriticalChars])/) ) { if ( $b_Windows and m/$Q/ ) { print "\n $Q$_$Q\n*** contains quotes.\n"; next; } for my $Ignore ( @Ignores ) { if ( m/$Ignore$/ ) { next FILE } } $Old = $_ ; m/^(.*$sep2)?([^$sep2]+)$/; $Dir = ( defined($1) ? $1 : ''); $_ = $2; #--------------------------------------------------------------------- # From now on : $Old = Dir/OldFilename # $_ = OldFilename #--------------------------------------------------------------------- print "\n $Q$Old$Q\n"; $ErrorMessage = &OutputAndErrorFromCommand(@List, $Old); if ( $? != 0 ) { print "*** $ErrorMessage\n" } else { #--------------------------------------------------------------- # Change accented Latin chars to non-accented chars. # Remove all diacritical marks after Latin chars. #--------------------------------------------------------------- eval "tr/$AccentedChars/$QuotedMetaNonAccenChars/"; s/([\ -\~])[$DiacriticalChars]+/$1/g; #--------------------------------------------------------------- # From now on : $Old = Dir/OldFilename # $_ = NewFilename #--------------------------------------------------------------- if ( $@ ) { warn $@ } else { $New = $Dir.$_; if ( $b_Windows or (not utf8::is_utf8($Dir)) ) # Weird { utf8::decode($New) } # but necessary $News{$Old} = $New; push(@{$Olds{$New}}, $Old); } print "--> $Q$Dir$_$Q\n"; } } } close(FIND); #----------------------------------------------------------------------------- # Print list of duplicate non-accented file names #----------------------------------------------------------------------------- my $b_NoDuplicate = 1; for my $New ( sort keys %Olds ) { if ( scalar(@{$Olds{$New}}) > 1 ) { if ( $b_NoDuplicate ) { print "\n\nFollowing files would have same non-accented name ", ":\n"; $b_NoDuplicate = 0; } print "\n", map(' '.$_."\n", @{$Olds{$New}}), '--> ', $New, "\n"; for ( @{$Olds{$New}} ) { delete $News{$_} }; } } #----------------------------------------------------------------------------- # If there are NO file to rename, then exit #----------------------------------------------------------------------------- my $Number = scalar(keys %News); print "\n\n"; if ( $Number < 1 ) { print "There are NO file to rename\n"; exit; } #----------------------------------------------------------------------------- # Ask the user for global approval of renaming #----------------------------------------------------------------------------- if ( $b_Interactive ) { print "In order to really rename the ", $Number, " files which can safely be renamed, type 'rename' : "; $_ = <STDIN>; sleep 1; # Gives time to PERL to handle interrupts if ( not m/^rename$/i ) { exit 1 } } else { print $Number, " files will be renamed\n\n" } #----------------------------------------------------------------------------- # Rename accented file names sorted descending by name size #----------------------------------------------------------------------------- $Number = 0; my $Move = join(' ', @Move); for ( sort {length($b) <=> length($a)} keys %News ) { $ErrorMessage = &OutputAndErrorFromCommand(@Move, $_, $News{$_}); if ( $? == 0 ) { $Number++ } else { print "\n$Move $Q$_$Q\n", (' ' x length($Move)), " $Q$News{$_}$Q\n", ('*' x length($Move)), " $ErrorMessage\n" } } print "\n$Number files have been successfully renamed\n"; __END__ ```
I'm using this batch to rename folders and seems to work fine so far... In my case codepage is 1252, yours might be different. ``` mode con codepage select=1252 @echo off Setlocal enabledelayedexpansion ::folder only (/D option) for /R /D %%d in (*) do ( set an=%%~nd set bn=!an:.=_! set cn=!bn:-=_! set dn=!cn: =_! set en=!dn:Á=A! set fn=!en:É=E! set gn=!fn:Í=I! set hn=!gn:Ó=O! set in=!hn:Ú=U! set jn=!in:Ü=U! set kn=!jn:á=a! set ln=!kn:é=e! set mn=!ln:í=i! set nn=!mn:ó=o! set on=!nn:ú=u! set pn=!on:ü=u! set qn=!pn:Ñ=N! set zn=!on:ñ=n! set ax=%%~xd set bx=!ax:.=_! set cx=!bx:-=_! set dx=!cx: =_! set bx=!ax:.=_! set cx=!bx:-=_! set dx=!cx: =_! set ex=!dx:Á=A! set fx=!ex:É=E! set gx=!fx:Í=I! set hx=!gx:Ó=O! set ix=!hx:Ú=U! set jx=!ix:Ü=U! set kx=!jx:á=a! set lx=!kx:é=e! set mx=!lx:í=i! set nx=!mx:ó=o! set ox=!nx:ú=u! set px=!ox:ü=u! set qx=!px:Ñ=N! set zx=!ox:ñ=n! if [!an!]==[] (set zn=) if [!ax!]==[] (set zx=) set newname=!zn!!zx! if /i not [%%~nd%%~xd]==[!newname!] rename "%%d" !newname! ) endlocal pause ```
779,788
I want my machine to work only on Ethernet. I mean I want to remove the WiFi access in my Ubuntu.
2016/05/31
[ "https://askubuntu.com/questions/779788", "https://askubuntu.com", "https://askubuntu.com/users/545611/" ]
If you want to hard block wifi (that means completely turn the wifi chip off) then you must do it from bios settings (my laptop has also an external switch). If you want to soft block wifi (that means disable wifi from within the os) then you can do it with these 3 ways: * with a combination of `Fn` key and some other for example `F8` if you have a laptop. * by right clicking on network manager indicator on your panel and uncheck the `Enable Wi-Fi` option. * Finally by the command `sudo rfkill block wifi` (use the command `rfkill list` to check it).
The easiest way is to click the Network manager icon on top of the screen and disable Wi-Fi there.
779,788
I want my machine to work only on Ethernet. I mean I want to remove the WiFi access in my Ubuntu.
2016/05/31
[ "https://askubuntu.com/questions/779788", "https://askubuntu.com", "https://askubuntu.com/users/545611/" ]
If you want to hard block wifi (that means completely turn the wifi chip off) then you must do it from bios settings (my laptop has also an external switch). If you want to soft block wifi (that means disable wifi from within the os) then you can do it with these 3 ways: * with a combination of `Fn` key and some other for example `F8` if you have a laptop. * by right clicking on network manager indicator on your panel and uncheck the `Enable Wi-Fi` option. * Finally by the command `sudo rfkill block wifi` (use the command `rfkill list` to check it).
In `/etc/modprobe.d` add the below and reboot: ``` install iwlwifi /bin/true ```
46,689,384
There is a css file and I want to make two things: 1) Remove all webkit keyframes and surrounding whitespace characters like: ``` @keyframes outToLeft { to { opacity: 0; -webkit-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } } ``` 2) Remove all webkit prefixed properties and surrounding whitespace characters like: ``` -webkit-transform: translate3d(100%, 0, 0); ``` I tries to use %s but it doesn't work (maybe my construction wasn't right) What is the best way to do this?
2017/10/11
[ "https://Stackoverflow.com/questions/46689384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7013674/" ]
You need to add permission to your manifest first ``` <uses-permission android:name="android.permission.CALL_PHONE" /> ``` After permission added in manifest following code would work fine for you "Number\_to\_call" will be youe number that is need to be replaced ``` val call = Intent(Intent.ACTION_DIAL) call.setData(Uri.parse("tel:" +"Number_to_call")) startActivity(call) ```
You need to request the runtime permission, since Android 6.0 certain permissions require you to ask at install and again at runtime. Following the instructions [here](https://developer.android.com/training/permissions/requesting.html?hl=en-419) explains how to ask for permission at runtime.
46,689,384
There is a css file and I want to make two things: 1) Remove all webkit keyframes and surrounding whitespace characters like: ``` @keyframes outToLeft { to { opacity: 0; -webkit-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } } ``` 2) Remove all webkit prefixed properties and surrounding whitespace characters like: ``` -webkit-transform: translate3d(100%, 0, 0); ``` I tries to use %s but it doesn't work (maybe my construction wasn't right) What is the best way to do this?
2017/10/11
[ "https://Stackoverflow.com/questions/46689384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7013674/" ]
You need to add the run time permission. [Download the source code from here](http://deepshikhapuri.blogspot.in/2017/11/runtime-permission-in-android-kotlin.html) //Click function of layout: ``` rl_call.setOnClickListener { if (boolean_call) { phonecall() }else { fn_permission(Manifest.permission.CALL_PHONE,CALLMODE) } } ``` // Request permission response ``` fun fn_permission(permission:String,mode:Int){ requestPermissions(permission, object : PermissionCallBack { override fun permissionGranted() { super.permissionGranted() Log.v("Call permissions", "Granted") boolean_call=true phonecall() } override fun permissionDenied() { super.permissionDenied() Log.v("Call permissions", "Denied") boolean_call=false } }) } ``` // function to call intent ``` fun phonecall() { val intent = Intent(Intent.ACTION_CALL); intent.data = Uri.parse("tel:1234567890s") startActivity(intent) } ``` Thanks!
You need to request the runtime permission, since Android 6.0 certain permissions require you to ask at install and again at runtime. Following the instructions [here](https://developer.android.com/training/permissions/requesting.html?hl=en-419) explains how to ask for permission at runtime.
46,689,384
There is a css file and I want to make two things: 1) Remove all webkit keyframes and surrounding whitespace characters like: ``` @keyframes outToLeft { to { opacity: 0; -webkit-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); } } ``` 2) Remove all webkit prefixed properties and surrounding whitespace characters like: ``` -webkit-transform: translate3d(100%, 0, 0); ``` I tries to use %s but it doesn't work (maybe my construction wasn't right) What is the best way to do this?
2017/10/11
[ "https://Stackoverflow.com/questions/46689384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7013674/" ]
First you need to add permission to your `manifest` first : ``` <uses-permission android:name="android.permission.CALL_PHONE" /> ``` This bit of code is used on the place of your method : ``` fun buChargeEvent(view: View) { var number: Int = txtCharge.text.toString().toInt() val callIntent = Intent(Intent.ACTION_CALL) callIntent.data = Uri.parse("tel:$number") if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this as Activity, Manifest.permission.CALL_PHONE)) { } else { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE), MY_PERMISSIONS_REQUEST_CALL_PHONE) } } startActivity(callIntent) } ```
You need to request the runtime permission, since Android 6.0 certain permissions require you to ask at install and again at runtime. Following the instructions [here](https://developer.android.com/training/permissions/requesting.html?hl=en-419) explains how to ask for permission at runtime.