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
|
---|---|---|---|---|---|
5,062,100 | I have web pages that may or may not need to do some pre-processing before it can be displayed to the user. What I have done is to display this page with a message (e.g. "please wait ..."), then do an http-equiv refresh **to the same page**. When it refreshes to the same page, the pre-processing is done and the actual content is displayed.
Will this harm me in terms of SEO? | 2011/02/21 | [
"https://Stackoverflow.com/questions/5062100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253976/"
]
| I suppose the best way to think of it is that "static" means unchanging, and it is the *location* of the variable that is unchanging when when you switch between the different instances of a class. The main thing is to eradicate any thought from your mind that the *value* of a static variable is unchanging: it may even be changed by another instance of the same class. | >
> Definition of STATIC 1 : exerting
> force by reason of weight alone
> without motion 2 : of or relating to
> bodies at rest or forces in
> equilibrium 3 : showing little change
> 4 a :
> characterized by a lack of movement,
> animation, or progression b :
> producing an effect of repose or
> quiescence 5 a :
> standing or fixed in one place :
> stationary b of water : stored in a
> tank but not under pressure
>
>
>
just apply the definition to a variable... |
5,062,100 | I have web pages that may or may not need to do some pre-processing before it can be displayed to the user. What I have done is to display this page with a message (e.g. "please wait ..."), then do an http-equiv refresh **to the same page**. When it refreshes to the same page, the pre-processing is done and the actual content is displayed.
Will this harm me in terms of SEO? | 2011/02/21 | [
"https://Stackoverflow.com/questions/5062100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253976/"
]
| I suppose the best way to think of it is that "static" means unchanging, and it is the *location* of the variable that is unchanging when when you switch between the different instances of a class. The main thing is to eradicate any thought from your mind that the *value* of a static variable is unchanging: it may even be changed by another instance of the same class. | In Head First Java, there is a nice explanation of static. Static means stable not changing thats obvious from meaning and its quite obvious that it does not change.
Static mean sharing in Java. There is a nice picture where two child sharing one ice cream and showed static variable analogy. For more info please read Head First Java. |
29,767,059 | Chisel generate always blocks with only clock in sensivity list :
```
always @posedge(clk) begin
[...]
end
```
Is it possible to configure Module to use an asynchronous reset and generate an always block like this ?
```
always @(posedge clk or posedge reset) begin
[...]
end
``` | 2015/04/21 | [
"https://Stackoverflow.com/questions/29767059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4422957/"
]
| Since Chisel 3.2.0, there is support for synchronous, asynchronous, and abstract reset types. Based on the type of reset explicitly specified or inferred, you will get canonical synchronous or asynchronous Verilog output.
To try to show this more fully, consider the following `MultiIOModule` which has three resets:
* The implicit `reset` input which has an abstract reset type (this is "abstract reset")
* The explicit `syncReset` input which has a `Bool` type (this is "synchronous reset")
* The explicit `asyncReset` input which has an `AsyncReset` type (this is "asynchronous reset")
Using `withReset`, specific reset connections can then be used for different registers in the design:
```scala
import chisel3._
import chisel3.stage.ChiselStage
class Foo extends MultiIOModule {
val syncReset = IO(Input(Bool() ))
val asyncReset = IO(Input(AsyncReset()))
val in = IO(Input( Bool()))
val outAbstract = IO(Output(Bool()))
val outSync = IO(Output(Bool()))
val outAsync = IO(Output(Bool()))
val regAbstract = RegNext(in, init=0.U)
val regSync = withReset(syncReset) { RegNext(in, init=0.U) }
val regAsync = withReset(asyncReset) { RegNext(in, init=0.U) }
outAbstract := regAbstract
outSync := regSync
outAsync := regAsync
}
```
This then produces the following Verilog when compiled with: `(new ChiselStage).emitVerilog(new Foo)`:
```
module Foo(
input clock,
input reset,
input syncReset,
input asyncReset,
input in,
output outAbstract,
output outSync,
output outAsync
);
reg regAbstract;
reg regSync;
reg regAsync;
assign outAbstract = regAbstract;
assign outSync = regSync;
assign outAsync = regAsync;
always @(posedge clock) begin
if (reset) begin
regAbstract <= 1'h0;
end else begin
regAbstract <= in;
end
if (syncReset) begin
regSync <= 1'h0;
end else begin
regSync <= in;
end
end
always @(posedge clock or posedge asyncReset) begin
if (asyncReset) begin
regAsync <= 1'h0;
end else begin
regAsync <= in;
end
end
endmodule
```
Note: that in Chisel 3.2 the top-level abstract reset would always be set to synchronous reset. In Chisel 3.3.0, two traits were added: `RequireSyncReset` and `RequireAsyncReset`. These can be used to change the reset type of the register connected to `regAbstract` from synchronous to asynchronous. Recompiling the design with `(new ChiselStage).emitVerilog(new Foo with RequireAsyncReset)`, changes the `regAbstract` logic to
```
always @(posedge clock or posedge reset) begin
if (reset) begin
regAbstract <= 1'h0;
end else begin
regAbstract <= in;
end
end
```
For more information, the [Chisel website has more information on resets](https://www.chisel-lang.org/chisel3/reset.html). | Chisel versions prior to 3.2.0 do not have support for asynchronous resets.
It looks like the way to do this in Chisel is to use synchronous resets:
```
always @posedge(clk) begin
if (reset) begin
[...]
end
else
[...]
end
end
```
For more discussion on the topic:
<https://groups.google.com/forum/#!topic/chisel-users/4cc4SyB5mk8> |
12,894,120 | I want to send an SMS, but not using the SmsManager class. I want to do it with the native SMS app which is there on an Android phone.
And here is the twist : I do NOT want to launch the native app while doing it. Is there some format of intent which can send an sms directly (given the sms-body and the phone number to send it to) via the native app (without the user having to click 'send').
I googled the same, but all results and responses simply launched the native sms, waiting for user to manually send the SMS. I have seen this being implemented in some apps like 'MightyText' and wish to implement in my app as well.
Please help ! | 2012/10/15 | [
"https://Stackoverflow.com/questions/12894120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877972/"
]
| Ok, so you want to send a SMS, without using SmsManager and plus it should show up in your native SMS app list?
Firstly, you cannot send SMS bypassing **SmsManager**. If you look at the source code of all native messaging app for Samsung Galaxy Nexus, it will invoke SmsManager on button click.
so, the below piece of code as posted above is correct
```
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
```
Secondly, after sending the message, native apps put it into into **SMS ContentProvider**
follow this [How to save SMS to inbox in android?](https://stackoverflow.com/questions/642076/how-to-save-sms-to-inbox-in-android)
Word of caution is that now adding to this is not supported. So you may have to resort to a hack to add it into the sent box. | If you only have `ACTION_SENDTO`, then, of course, any application that can send will pop up.
You need to add a filter for SMS
* with URL. See <https://stackoverflow.com/a/2372665/94363>
* or with content type <https://stackoverflow.com/a/10613013/94363> |
12,894,120 | I want to send an SMS, but not using the SmsManager class. I want to do it with the native SMS app which is there on an Android phone.
And here is the twist : I do NOT want to launch the native app while doing it. Is there some format of intent which can send an sms directly (given the sms-body and the phone number to send it to) via the native app (without the user having to click 'send').
I googled the same, but all results and responses simply launched the native sms, waiting for user to manually send the SMS. I have seen this being implemented in some apps like 'MightyText' and wish to implement in my app as well.
Please help ! | 2012/10/15 | [
"https://Stackoverflow.com/questions/12894120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877972/"
]
| Using the SmsManager will send the sms through the system but will not put it in the SMS content provider as was mentioned earlier. Hence any native messaging app will not see it.
To do so, you have to add it manually via the SMS content provider AFTER you send the message normally via SmsManager. Here's some sample code to help:
```
ContentValues values = new ContentValues();
values.put("address", "+12345678"); // phone number to send
values.put("date", System.currentTimeMillis()+"");
values.put("read", "1"); // if you want to mark is as unread set to 0
values.put("type", "2"); // 2 means sent message
values.put("body", "This is my message!");
Uri uri = Uri.parse("content://sms/");
Uri rowUri = context.getContentResolver().insert(uri,values);
```
And that's all. After that you'll notice that it's added and the native messaging app displays it normally.
Please click "accept" answer if it works out for you. | If you only have `ACTION_SENDTO`, then, of course, any application that can send will pop up.
You need to add a filter for SMS
* with URL. See <https://stackoverflow.com/a/2372665/94363>
* or with content type <https://stackoverflow.com/a/10613013/94363> |
12,894,120 | I want to send an SMS, but not using the SmsManager class. I want to do it with the native SMS app which is there on an Android phone.
And here is the twist : I do NOT want to launch the native app while doing it. Is there some format of intent which can send an sms directly (given the sms-body and the phone number to send it to) via the native app (without the user having to click 'send').
I googled the same, but all results and responses simply launched the native sms, waiting for user to manually send the SMS. I have seen this being implemented in some apps like 'MightyText' and wish to implement in my app as well.
Please help ! | 2012/10/15 | [
"https://Stackoverflow.com/questions/12894120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877972/"
]
| Ok, so you want to send a SMS, without using SmsManager and plus it should show up in your native SMS app list?
Firstly, you cannot send SMS bypassing **SmsManager**. If you look at the source code of all native messaging app for Samsung Galaxy Nexus, it will invoke SmsManager on button click.
so, the below piece of code as posted above is correct
```
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
```
Secondly, after sending the message, native apps put it into into **SMS ContentProvider**
follow this [How to save SMS to inbox in android?](https://stackoverflow.com/questions/642076/how-to-save-sms-to-inbox-in-android)
Word of caution is that now adding to this is not supported. So you may have to resort to a hack to add it into the sent box. | I have done something similar in a project I was working on. You need to use [SmsManager](http://developer.android.com/reference/android/telephony/gsm/SmsManager.html)
It would be something like this -
```
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
```
You can use this to send an SMS programatically. |
12,894,120 | I want to send an SMS, but not using the SmsManager class. I want to do it with the native SMS app which is there on an Android phone.
And here is the twist : I do NOT want to launch the native app while doing it. Is there some format of intent which can send an sms directly (given the sms-body and the phone number to send it to) via the native app (without the user having to click 'send').
I googled the same, but all results and responses simply launched the native sms, waiting for user to manually send the SMS. I have seen this being implemented in some apps like 'MightyText' and wish to implement in my app as well.
Please help ! | 2012/10/15 | [
"https://Stackoverflow.com/questions/12894120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877972/"
]
| Using the SmsManager will send the sms through the system but will not put it in the SMS content provider as was mentioned earlier. Hence any native messaging app will not see it.
To do so, you have to add it manually via the SMS content provider AFTER you send the message normally via SmsManager. Here's some sample code to help:
```
ContentValues values = new ContentValues();
values.put("address", "+12345678"); // phone number to send
values.put("date", System.currentTimeMillis()+"");
values.put("read", "1"); // if you want to mark is as unread set to 0
values.put("type", "2"); // 2 means sent message
values.put("body", "This is my message!");
Uri uri = Uri.parse("content://sms/");
Uri rowUri = context.getContentResolver().insert(uri,values);
```
And that's all. After that you'll notice that it's added and the native messaging app displays it normally.
Please click "accept" answer if it works out for you. | I have done something similar in a project I was working on. You need to use [SmsManager](http://developer.android.com/reference/android/telephony/gsm/SmsManager.html)
It would be something like this -
```
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
```
You can use this to send an SMS programatically. |
12,894,120 | I want to send an SMS, but not using the SmsManager class. I want to do it with the native SMS app which is there on an Android phone.
And here is the twist : I do NOT want to launch the native app while doing it. Is there some format of intent which can send an sms directly (given the sms-body and the phone number to send it to) via the native app (without the user having to click 'send').
I googled the same, but all results and responses simply launched the native sms, waiting for user to manually send the SMS. I have seen this being implemented in some apps like 'MightyText' and wish to implement in my app as well.
Please help ! | 2012/10/15 | [
"https://Stackoverflow.com/questions/12894120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877972/"
]
| Using the SmsManager will send the sms through the system but will not put it in the SMS content provider as was mentioned earlier. Hence any native messaging app will not see it.
To do so, you have to add it manually via the SMS content provider AFTER you send the message normally via SmsManager. Here's some sample code to help:
```
ContentValues values = new ContentValues();
values.put("address", "+12345678"); // phone number to send
values.put("date", System.currentTimeMillis()+"");
values.put("read", "1"); // if you want to mark is as unread set to 0
values.put("type", "2"); // 2 means sent message
values.put("body", "This is my message!");
Uri uri = Uri.parse("content://sms/");
Uri rowUri = context.getContentResolver().insert(uri,values);
```
And that's all. After that you'll notice that it's added and the native messaging app displays it normally.
Please click "accept" answer if it works out for you. | Ok, so you want to send a SMS, without using SmsManager and plus it should show up in your native SMS app list?
Firstly, you cannot send SMS bypassing **SmsManager**. If you look at the source code of all native messaging app for Samsung Galaxy Nexus, it will invoke SmsManager on button click.
so, the below piece of code as posted above is correct
```
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
```
Secondly, after sending the message, native apps put it into into **SMS ContentProvider**
follow this [How to save SMS to inbox in android?](https://stackoverflow.com/questions/642076/how-to-save-sms-to-inbox-in-android)
Word of caution is that now adding to this is not supported. So you may have to resort to a hack to add it into the sent box. |
12,894,120 | I want to send an SMS, but not using the SmsManager class. I want to do it with the native SMS app which is there on an Android phone.
And here is the twist : I do NOT want to launch the native app while doing it. Is there some format of intent which can send an sms directly (given the sms-body and the phone number to send it to) via the native app (without the user having to click 'send').
I googled the same, but all results and responses simply launched the native sms, waiting for user to manually send the SMS. I have seen this being implemented in some apps like 'MightyText' and wish to implement in my app as well.
Please help ! | 2012/10/15 | [
"https://Stackoverflow.com/questions/12894120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877972/"
]
| Ok, so you want to send a SMS, without using SmsManager and plus it should show up in your native SMS app list?
Firstly, you cannot send SMS bypassing **SmsManager**. If you look at the source code of all native messaging app for Samsung Galaxy Nexus, it will invoke SmsManager on button click.
so, the below piece of code as posted above is correct
```
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
```
Secondly, after sending the message, native apps put it into into **SMS ContentProvider**
follow this [How to save SMS to inbox in android?](https://stackoverflow.com/questions/642076/how-to-save-sms-to-inbox-in-android)
Word of caution is that now adding to this is not supported. So you may have to resort to a hack to add it into the sent box. | Try this:
```
String phoneNo = textPhoneNo.getText().toString();
String sms = textSMS.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
``` |
12,894,120 | I want to send an SMS, but not using the SmsManager class. I want to do it with the native SMS app which is there on an Android phone.
And here is the twist : I do NOT want to launch the native app while doing it. Is there some format of intent which can send an sms directly (given the sms-body and the phone number to send it to) via the native app (without the user having to click 'send').
I googled the same, but all results and responses simply launched the native sms, waiting for user to manually send the SMS. I have seen this being implemented in some apps like 'MightyText' and wish to implement in my app as well.
Please help ! | 2012/10/15 | [
"https://Stackoverflow.com/questions/12894120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877972/"
]
| Using the SmsManager will send the sms through the system but will not put it in the SMS content provider as was mentioned earlier. Hence any native messaging app will not see it.
To do so, you have to add it manually via the SMS content provider AFTER you send the message normally via SmsManager. Here's some sample code to help:
```
ContentValues values = new ContentValues();
values.put("address", "+12345678"); // phone number to send
values.put("date", System.currentTimeMillis()+"");
values.put("read", "1"); // if you want to mark is as unread set to 0
values.put("type", "2"); // 2 means sent message
values.put("body", "This is my message!");
Uri uri = Uri.parse("content://sms/");
Uri rowUri = context.getContentResolver().insert(uri,values);
```
And that's all. After that you'll notice that it's added and the native messaging app displays it normally.
Please click "accept" answer if it works out for you. | Try this:
```
String phoneNo = textPhoneNo.getText().toString();
String sms = textSMS.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
``` |
20,955 | My cat, Marty, is a real fraidy cat. He doesn't like most new people, but eventually he'll grow to like them.
We recently moved into my grandpa's house a city over from where we used to live. Currently, my cat is hiding under my bed. Usually at night, he'll come out from hiding and come downstairs when he knows it's just me, my sister, my brother and my mom downstairs, but sometimes when he's hungry he'll come out during the day, but only if one of us comes down the stairs with him. He's gotten pretty used to my uncle, he lets him pet him for a while, but he hasn't gotten used to my grandpa.
Also at night when we all go to bed he'll follow us upstairs, and he'll always sleep on my bed with me. He's not interested in sleeping on anyone elses bed, even if my sister picks him up and puts him on her bed, he usually just jumps right off and jumps onto my bed.
Any help would be appreciated. | 2018/07/25 | [
"https://pets.stackexchange.com/questions/20955",
"https://pets.stackexchange.com",
"https://pets.stackexchange.com/users/12615/"
]
| Two weeks isn't all that long. Our first two cats were incredibly shy (they lived in the wild in a prison, where they had learned to stay quiet and out of sight).
It took them *months* to just be out in the open in the living room. We had kept them in a single room for the first two weeks. We then also gave them the hallway, and it took them over a week to actually want to go into the hallway. The same happened when we opened the door to the living room. And for two more months, they would never go downstairs without us, or during the day.
Your cat is by itself, getting to meet several new people, and also shy. I would give her a few extra weeks (if not months) before you see full integration into the household. | Cats, unlike dogs, are teritorial creatures - they get used to the place. They do not take well when moving. Two weeks is normal, it may take months. I would suggest you do not force him. He will explore when and where he feels comfortable. As long as he eats and drinks water, uses his litter box he will be fine.
It is normal for him to become more active during the night, that is when they hunt and explore. Cat's are curious by nature. Hiding makes him feel safe, so let him be, and don't try to force him out.
Toys, treats, cat nip may motivate him but that depends a lot on the breed and character of the cat, it won't hurt to try. Just don't put his food, water and box at a place he cannot find it or doesn't want to go. |
20,955 | My cat, Marty, is a real fraidy cat. He doesn't like most new people, but eventually he'll grow to like them.
We recently moved into my grandpa's house a city over from where we used to live. Currently, my cat is hiding under my bed. Usually at night, he'll come out from hiding and come downstairs when he knows it's just me, my sister, my brother and my mom downstairs, but sometimes when he's hungry he'll come out during the day, but only if one of us comes down the stairs with him. He's gotten pretty used to my uncle, he lets him pet him for a while, but he hasn't gotten used to my grandpa.
Also at night when we all go to bed he'll follow us upstairs, and he'll always sleep on my bed with me. He's not interested in sleeping on anyone elses bed, even if my sister picks him up and puts him on her bed, he usually just jumps right off and jumps onto my bed.
Any help would be appreciated. | 2018/07/25 | [
"https://pets.stackexchange.com/questions/20955",
"https://pets.stackexchange.com",
"https://pets.stackexchange.com/users/12615/"
]
| If he has something he likes: toys, bed or even litter in another litter box, placing it out in the open where you want him to be could help him feel more comfortable. If your kitty likes treats you could encourage him by putting some treats where you want him to be. You could also try this with catnip instead of treats. | Cats, unlike dogs, are teritorial creatures - they get used to the place. They do not take well when moving. Two weeks is normal, it may take months. I would suggest you do not force him. He will explore when and where he feels comfortable. As long as he eats and drinks water, uses his litter box he will be fine.
It is normal for him to become more active during the night, that is when they hunt and explore. Cat's are curious by nature. Hiding makes him feel safe, so let him be, and don't try to force him out.
Toys, treats, cat nip may motivate him but that depends a lot on the breed and character of the cat, it won't hurt to try. Just don't put his food, water and box at a place he cannot find it or doesn't want to go. |
19,784,868 | I'm trying to convert the following MATLAB code to Python and am having trouble finding a solution that works in any reasonable amount of time.
```
M = diag(sum(a)) - a;
where = vertcat(in, out);
M(where,:) = 0;
M(where,where) = 1;
```
Here, a is a sparse matrix and where is a vector (as are in/out). The solution I have using Python is:
```
M = scipy.sparse.diags([degs], [0]) - A
where = numpy.hstack((inVs, outVs)).astype(int)
M = scipy.sparse.lil_matrix(M)
M[where, :] = 0 # This is the slowest line
M[where, where] = 1
M = scipy.sparse.csc_matrix(M)
```
But since A is 334863x334863, this takes like three minutes. If anyone has any suggestions on how to make this faster, please contribute them! For comparison, MATLAB does this same step imperceptibly fast.
Thanks! | 2013/11/05 | [
"https://Stackoverflow.com/questions/19784868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2137996/"
]
| The solution I use for similar task [attributes to @seberg](https://stackoverflow.com/a/12130287/1265154) and do not convert to `lil` format:
```
import scipy.sparse
import numpy
import time
def csr_row_set_nz_to_val(csr, row, value=0):
"""Set all nonzero elements (elements currently in the sparsity pattern)
to the given value. Useful to set to 0 mostly.
"""
if not isinstance(csr, scipy.sparse.csr_matrix):
raise ValueError('Matrix given must be of CSR format.')
csr.data[csr.indptr[row]:csr.indptr[row+1]] = value
def csr_rows_set_nz_to_val(csr, rows, value=0):
for row in rows:
csr_row_set_nz_to_val(csr, row)
if value == 0:
csr.eliminate_zeros()
```
wrap your evaluations with timing
```
def evaluate(size):
degs = [1]*size
inVs = list(xrange(1, size, size/25))
outVs = list(xrange(5, size, size/25))
where = numpy.hstack((inVs, outVs)).astype(int)
start_time = time.time()
A = scipy.sparse.csc_matrix((size, size))
M = scipy.sparse.diags([degs], [0]) - A
csr_rows_set_nz_to_val(M, where)
return time.time()-start_time
```
and test its performance:
```
>>> print 'elapsed %.5f seconds' % evaluate(334863)
elapsed 0.53054 seconds
``` | A slightly different take on alko/seberg's approach. I find for loops disturbing, so I spent the better part of this morning figuring a way to get rid of it. The following is not always faster than the other approach. It performs better the more rows there are to be zeroed and the sparser the matrix:
```
def csr_zero_rows(csr, rows_to_zero):
rows, cols = csr.shape
mask = np.ones((rows,), dtype=np.bool)
mask[rows_to_zero] = False
nnz_per_row = np.diff(csr.indptr)
mask = np.repeat(mask, nnz_per_row)
nnz_per_row[rows_to_zero] = 0
csr.data = csr.data[mask]
csr.indices = csr.indices[mask]
csr.indptr[1:] = np.cumsum(nnz_per_row)
```
And to test drive both approaches:
```
rows, cols = 334863, 334863
a = sps.rand(rows, cols, density=0.00001, format='csr')
b = a.copy()
rows_to_zero = np.random.choice(np.arange(rows), size=10000, replace=False)
In [117]: a
Out[117]:
<334863x334863 sparse matrix of type '<type 'numpy.float64'>'
with 1121332 stored elements in Compressed Sparse Row format>
In [118]: %timeit -n1 -r1 csr_rows_set_nz_to_val(a, rows_to_zero)
1 loops, best of 1: 75.8 ms per loop
In [119]: %timeit -n1 -r1 csr_zero_rows(b, rows_to_zero)
1 loops, best of 1: 32.5 ms per loop
```
And of course:
```
np.allclose(a.data, b.data)
Out[122]: True
np.allclose(a.indices, b.indices)
Out[123]: True
np.allclose(a.indptr, b.indptr)
Out[124]: True
``` |
19,784,868 | I'm trying to convert the following MATLAB code to Python and am having trouble finding a solution that works in any reasonable amount of time.
```
M = diag(sum(a)) - a;
where = vertcat(in, out);
M(where,:) = 0;
M(where,where) = 1;
```
Here, a is a sparse matrix and where is a vector (as are in/out). The solution I have using Python is:
```
M = scipy.sparse.diags([degs], [0]) - A
where = numpy.hstack((inVs, outVs)).astype(int)
M = scipy.sparse.lil_matrix(M)
M[where, :] = 0 # This is the slowest line
M[where, where] = 1
M = scipy.sparse.csc_matrix(M)
```
But since A is 334863x334863, this takes like three minutes. If anyone has any suggestions on how to make this faster, please contribute them! For comparison, MATLAB does this same step imperceptibly fast.
Thanks! | 2013/11/05 | [
"https://Stackoverflow.com/questions/19784868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2137996/"
]
| The solution I use for similar task [attributes to @seberg](https://stackoverflow.com/a/12130287/1265154) and do not convert to `lil` format:
```
import scipy.sparse
import numpy
import time
def csr_row_set_nz_to_val(csr, row, value=0):
"""Set all nonzero elements (elements currently in the sparsity pattern)
to the given value. Useful to set to 0 mostly.
"""
if not isinstance(csr, scipy.sparse.csr_matrix):
raise ValueError('Matrix given must be of CSR format.')
csr.data[csr.indptr[row]:csr.indptr[row+1]] = value
def csr_rows_set_nz_to_val(csr, rows, value=0):
for row in rows:
csr_row_set_nz_to_val(csr, row)
if value == 0:
csr.eliminate_zeros()
```
wrap your evaluations with timing
```
def evaluate(size):
degs = [1]*size
inVs = list(xrange(1, size, size/25))
outVs = list(xrange(5, size, size/25))
where = numpy.hstack((inVs, outVs)).astype(int)
start_time = time.time()
A = scipy.sparse.csc_matrix((size, size))
M = scipy.sparse.diags([degs], [0]) - A
csr_rows_set_nz_to_val(M, where)
return time.time()-start_time
```
and test its performance:
```
>>> print 'elapsed %.5f seconds' % evaluate(334863)
elapsed 0.53054 seconds
``` | If you dislike digging around in the guts of the sparse matrices, you can also use sparse matrix multiplication with a diagonal matrix:
```
def zero_rows(M, rows_to_zero):
ixs = numpy.ones(M.shape[0], int)
ixs[rows_to_zero] = 0
D = sparse.diags(ixs)
res = D * M
return res
``` |
19,784,868 | I'm trying to convert the following MATLAB code to Python and am having trouble finding a solution that works in any reasonable amount of time.
```
M = diag(sum(a)) - a;
where = vertcat(in, out);
M(where,:) = 0;
M(where,where) = 1;
```
Here, a is a sparse matrix and where is a vector (as are in/out). The solution I have using Python is:
```
M = scipy.sparse.diags([degs], [0]) - A
where = numpy.hstack((inVs, outVs)).astype(int)
M = scipy.sparse.lil_matrix(M)
M[where, :] = 0 # This is the slowest line
M[where, where] = 1
M = scipy.sparse.csc_matrix(M)
```
But since A is 334863x334863, this takes like three minutes. If anyone has any suggestions on how to make this faster, please contribute them! For comparison, MATLAB does this same step imperceptibly fast.
Thanks! | 2013/11/05 | [
"https://Stackoverflow.com/questions/19784868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2137996/"
]
| A slightly different take on alko/seberg's approach. I find for loops disturbing, so I spent the better part of this morning figuring a way to get rid of it. The following is not always faster than the other approach. It performs better the more rows there are to be zeroed and the sparser the matrix:
```
def csr_zero_rows(csr, rows_to_zero):
rows, cols = csr.shape
mask = np.ones((rows,), dtype=np.bool)
mask[rows_to_zero] = False
nnz_per_row = np.diff(csr.indptr)
mask = np.repeat(mask, nnz_per_row)
nnz_per_row[rows_to_zero] = 0
csr.data = csr.data[mask]
csr.indices = csr.indices[mask]
csr.indptr[1:] = np.cumsum(nnz_per_row)
```
And to test drive both approaches:
```
rows, cols = 334863, 334863
a = sps.rand(rows, cols, density=0.00001, format='csr')
b = a.copy()
rows_to_zero = np.random.choice(np.arange(rows), size=10000, replace=False)
In [117]: a
Out[117]:
<334863x334863 sparse matrix of type '<type 'numpy.float64'>'
with 1121332 stored elements in Compressed Sparse Row format>
In [118]: %timeit -n1 -r1 csr_rows_set_nz_to_val(a, rows_to_zero)
1 loops, best of 1: 75.8 ms per loop
In [119]: %timeit -n1 -r1 csr_zero_rows(b, rows_to_zero)
1 loops, best of 1: 32.5 ms per loop
```
And of course:
```
np.allclose(a.data, b.data)
Out[122]: True
np.allclose(a.indices, b.indices)
Out[123]: True
np.allclose(a.indptr, b.indptr)
Out[124]: True
``` | If you dislike digging around in the guts of the sparse matrices, you can also use sparse matrix multiplication with a diagonal matrix:
```
def zero_rows(M, rows_to_zero):
ixs = numpy.ones(M.shape[0], int)
ixs[rows_to_zero] = 0
D = sparse.diags(ixs)
res = D * M
return res
``` |
48,101,266 | I am building an app on Glitch with express js which requires the user to upload multiple files. Here is my code:
```js
var express = require('express');
var cors= require('cors');
var bodyParser= require('body-parser');
var contexts= require('./contexts');
var path= require('path');
var fileUpload= require('express-fileupload');
var multer= require('multer');
var upload = multer();
var app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(fileUpload());
app.set('view engine', 'ejs');
app.set('views', 'views');
app.use(express.static('views/'));
//here express-fileuploads works fine
app.post('/getcontexts', function (req,res) {
var context=contexts.get(req.files.file.data.toString());
res.render('rast', {length: context.length, content : context});
});
//this is when I get an empty array
app.post('/getrast', upload.array('rastfiles'), function (req, res) {
res.json({data: req.files});
});
var listener = app.listen(process.env.PORT, function () {
console.log('SERVER STARTED ON PORT ' + listener.address().port);
});
```
and here is the ejs form I use:
```html
<form action="/getrast" method="POST" enctype="multipart/form-data">
<label for="rastfiles">Please select your Rast genome files with .txt extension</label>
<br>
<input type="file" id="file" name="rastfiles" class="inputFile" multiple>
<br>
<input type="submit" value="Run" id="sub">
</form>
```
I already used express-fileupload to upload a single file and it worked just fine. However, when I use multer to upload multiple files I get and empty array when logging req,files into the console. Any idea why this might be happening?
I'd really appreciate any help. Thanks! | 2018/01/04 | [
"https://Stackoverflow.com/questions/48101266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8371765/"
]
| The reason why multer was not working is because express-fileupload was already being used as middleware for file uploading, so commenting out this line:
```
app.use(fileUpload())
```
fixed the problem for me. | This is from multer doc:
>
> Multer accepts an options object, the most basic of which is the dest
> property, which tells Multer where to upload the files. **In case you
> omit the options object, the files will be kept in memory and never
> written to disk.**
>
>
>
that's mean you need to define at least `dest` option:
```
var upload = multer({ dest: 'uploads/' });
``` |
47,466,630 | i am developing plugin where i have to update the single record onchanging the select option element , i tried using wordpres codex way ,but i am struck can please anyone help me out here, below is my code
```js
function ajaxFunction(str,id) {
var payment_selected = str;
var id=id;
var queryString = '&id_took='+id+'&sel='+payment_selected;
var data = {
'action' : 'my_action',
'payment_selected': payment_selected,
'id' : id
};
jQuery.post(admin_url("admin-ajax.php"), data, function(response) {
jQuery("#status").html(response);
});
}
```
```html
/* this is a php file , i used in the plugin where below html form appears */
<?php
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$id_selected = $_POST['payment_selected'];
$id = $_POST['id'];
$table_name_payment = $wpdb->prefix . "online_booking_system_model";
$result_pay = $wpdb->query($wpdb->prepare("UPDATE $table_name_payment SET payment_status = $id_selected WHERE id=$id"));
echo "success";
?>
/* this is the html file */
foreach ($rows as $row) { ?>
<table>
<td><?php echo $row->payment_status; ?></td>
<select name='payment_select' id="payment_select" onchange="ajaxFunction(this.value,<?php echo $row->id ?>)">
<option value="Payment Due">Payment Due</option>
<option value="Payment completed">Payment Completed</option>
</select>
<?php } ?>
<table>
<div id="status"></div>
``` | 2017/11/24 | [
"https://Stackoverflow.com/questions/47466630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6737108/"
]
| AS it is clear from the html that id and classnames are same for the elements :
so you can modify below code as per your requirement (Whether you want to click first , second or third element )
ReadOnlyCollection allelements = driver.FindElement(By.Id("txtSearch"));
```
foreach (IWebElement element in allelements)
{
//Add logic here whether you want click on first or second or nth element
element.Click();
}
``` | Always better to use Id instead of ClassName, Because Id is unique but ClassName may be multiple.
```
var searchBox = driver.FindElement(By.Id("txtSearch"));
searchBox.Clear();
searchBox.SendKeys("xyz");
```
One more question, in your html I see two input text with the same Id. You should commenting one input. |
66,957,425 | I need to calculate the mean per group (i.e, per Coordinates) of the sample table below without losing any of the columns (the real table has over 40,000 rows with different states,location coordinates and type) So this:
| State | Location Coordinates | Type | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| California | West | Debt | 234 | 56 | 79 | 890 | 24 | 29 | 20 | 24 | 26 |
| Nevada | West | Debt | 45 | 54 | 87 | 769 | 54 | 76 | 90 | 87 | 98 |
Would become this :
| State | Location Coordinates | Type | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| West | West | Debt | 234 | 56 | 79 | 890 | 24 | 29 | 20 | 24 | 26 |
When I use aggregate (df <- aggregate(df[,4:length(df)], list(df$Coordinates), mean). It removes the State and City columns.
| Location Coordinates | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| West | 235 | 55 | 83 | 843 | 24 | 29 | 20 | 24 | 26 | Debt | 54 | 769 | 76 | 87 |
And when I use sqldf it averages the year and becomes this:
| State | Location Coordinates | Type | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| West | West | Debt | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 |
Any suggestions? | 2021/04/05 | [
"https://Stackoverflow.com/questions/66957425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14032099/"
]
| Use [`Series.dt.time`](https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.time.html):
```
import pandas as pd
# sample
df = pd.DataFrame({'Time': ['00:00:05', '00:00:10', '00:10:00']})
df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S').dt.time
print(type(df.Time[0]))
[out]:
<class 'datetime.time'>
```
For adding or subtracting `time`, you can do this:
```
pd.Timedelta(df.Time - t1).seconds / 3600.0
``` | you can use `timedelta`:
```
df['Time'] = pd.to_timedelta(df['Time'])
```
---
To calculate minutes:
```
pd.to_timedelta(df.time).dt.seconds/60
``` |
823,004 | For example, I want the first entry in Column B (B1) to show A5, then B2 shows A10, then B3 shows A15.
How would I go about doing this? | 2014/10/09 | [
"https://superuser.com/questions/823004",
"https://superuser.com",
"https://superuser.com/users/147795/"
]
| For excel you can put this in B1 and drag down
```
=INDEX($A$1:$A$100,5*(ROWS($B$1:B1)-1))
```
To start with A5 instead of A1, use this
```
=INDEX($A$1:$A$100,5*(ROWS($B$1:B1)))
``` | Do you want the cell to take the value of A5, A10 etc? or the actual value "A5", "A10". If you want the value from the cells Raystafarian has a good answer. If you want the values "A5" etc use
```
= "A" & 5*rows("$B$1:$B$1)
``` |
28,949,902 | We are receiving an SMTP 4.4.1 connection time out exception every so often when attempting to send mail in C#. So far we have found no pattern as to when the issue occurs, such as the time of day.
The exception thrown is:
>
> System.Net.Mail.SmtpException: Service not available, closing transmission channel. The server response was: 4.4.1 Connection timed out
>
>
>
Up to 30 emails at anyone time are sent and 9 times out of 10 all are sent successfully. When we run into the 4.4.1 exception a number of the emails are sent and the remaining 1 or 2 are not.
Unfortunately, I don't have access to the clients Exchange server, only the application server where our application is running from. So I'm working with the host on this. The Event Log has been checked on the application server, the only thing found was the following warning from a source McLogEvent:
>
> Would be blocked by port blocking rule (rule is in warn-only mode) (Anti-virus Standard Protection: Prevent mass mailing worms from sending mail).
>
>
>
Has anyone came across this issue before or know of a possible cause? | 2015/03/09 | [
"https://Stackoverflow.com/questions/28949902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4598265/"
]
| You must use a major upgrade if you remove components. See [Changing the Product Code](https://msdn.microsoft.com/en-us/library/aa367850%28v=vs.85%29.aspx) for the list of things that cannot be done with minor upgrades. | Actually, it's not logical :) If you have a) really done a successful major upgrade and b) those Dlls were only in the older version and not in the newer upgrade you installed then they should not be there at all. The old product is no longer there if the upgrade was successful, and there is no old version to have those files - it's uninstalled by the upgrade. If you have two entries in Programs&Features then you didn't do a correct replacement upgrade and that older product is still installed. If you have only one entry in Programs&Features then there is most likely something wrong with your use of component ids. It really is all about those ids sometimes. For example, if you used the same component id in the upgrade for something else in the new upgrade then Windows Installer cannot ref count that id (associated with that older Dll) down to zero and remove the older DLL. Make sure the component ids for those older Dlls are not in the new upgrade. Apart from that, if you ever marked those Dlls as Permanent or SharedLegacy then they won't be uninstalled when the upgrade removes the older product.
Before deciding what to do you should figure out exactly what is going on. You cannot install the same ProductCode twice, so you are going into some kind of maintenance mode are you are NOT doing an upgrade and you have NOT installed a new product. If you want to actually do an upgrade then use the WiX majorupgrade element. |
28,949,902 | We are receiving an SMTP 4.4.1 connection time out exception every so often when attempting to send mail in C#. So far we have found no pattern as to when the issue occurs, such as the time of day.
The exception thrown is:
>
> System.Net.Mail.SmtpException: Service not available, closing transmission channel. The server response was: 4.4.1 Connection timed out
>
>
>
Up to 30 emails at anyone time are sent and 9 times out of 10 all are sent successfully. When we run into the 4.4.1 exception a number of the emails are sent and the remaining 1 or 2 are not.
Unfortunately, I don't have access to the clients Exchange server, only the application server where our application is running from. So I'm working with the host on this. The Event Log has been checked on the application server, the only thing found was the following warning from a source McLogEvent:
>
> Would be blocked by port blocking rule (rule is in warn-only mode) (Anti-virus Standard Protection: Prevent mass mailing worms from sending mail).
>
>
>
Has anyone came across this issue before or know of a possible cause? | 2015/03/09 | [
"https://Stackoverflow.com/questions/28949902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4598265/"
]
| Actually, it's not logical :) If you have a) really done a successful major upgrade and b) those Dlls were only in the older version and not in the newer upgrade you installed then they should not be there at all. The old product is no longer there if the upgrade was successful, and there is no old version to have those files - it's uninstalled by the upgrade. If you have two entries in Programs&Features then you didn't do a correct replacement upgrade and that older product is still installed. If you have only one entry in Programs&Features then there is most likely something wrong with your use of component ids. It really is all about those ids sometimes. For example, if you used the same component id in the upgrade for something else in the new upgrade then Windows Installer cannot ref count that id (associated with that older Dll) down to zero and remove the older DLL. Make sure the component ids for those older Dlls are not in the new upgrade. Apart from that, if you ever marked those Dlls as Permanent or SharedLegacy then they won't be uninstalled when the upgrade removes the older product.
Before deciding what to do you should figure out exactly what is going on. You cannot install the same ProductCode twice, so you are going into some kind of maintenance mode are you are NOT doing an upgrade and you have NOT installed a new product. If you want to actually do an upgrade then use the WiX majorupgrade element. | @Bob Arnson: I don't want to do a major upgrade as I want the previous version to be not uninstalled but upgraded. So I came up with a fix for now using RemoveFile tag under those components that specifies those file ids to be deleted in case they are present.
```
<RemoveFile Id = "id_to_be_removed" On = "uninstall" Name = "dll_name"/>
``` |
28,949,902 | We are receiving an SMTP 4.4.1 connection time out exception every so often when attempting to send mail in C#. So far we have found no pattern as to when the issue occurs, such as the time of day.
The exception thrown is:
>
> System.Net.Mail.SmtpException: Service not available, closing transmission channel. The server response was: 4.4.1 Connection timed out
>
>
>
Up to 30 emails at anyone time are sent and 9 times out of 10 all are sent successfully. When we run into the 4.4.1 exception a number of the emails are sent and the remaining 1 or 2 are not.
Unfortunately, I don't have access to the clients Exchange server, only the application server where our application is running from. So I'm working with the host on this. The Event Log has been checked on the application server, the only thing found was the following warning from a source McLogEvent:
>
> Would be blocked by port blocking rule (rule is in warn-only mode) (Anti-virus Standard Protection: Prevent mass mailing worms from sending mail).
>
>
>
Has anyone came across this issue before or know of a possible cause? | 2015/03/09 | [
"https://Stackoverflow.com/questions/28949902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4598265/"
]
| You must use a major upgrade if you remove components. See [Changing the Product Code](https://msdn.microsoft.com/en-us/library/aa367850%28v=vs.85%29.aspx) for the list of things that cannot be done with minor upgrades. | @Bob Arnson: I don't want to do a major upgrade as I want the previous version to be not uninstalled but upgraded. So I came up with a fix for now using RemoveFile tag under those components that specifies those file ids to be deleted in case they are present.
```
<RemoveFile Id = "id_to_be_removed" On = "uninstall" Name = "dll_name"/>
``` |
421,206 | I have a Linux VPS serving data on the internet that has a legitimate Domain name and SSL Certificate ( from GoDaddy.com ). I will refere to this server as "**www.myserver.com**". I also have a local Linux machine ( on my own LAN ) that I want to use to DNS spoof my internet facing Domain name ( www.myserver.com ) to it's own NGINX webserver running on that local machine.
I setup DNSMasq on the local machine to spoof that domain to it's local 192.x address and I verified from another machine on the LAN that dig reports the local address.
Local server dnsmaq spoof mapping:
```
cat /etc/dnsmasq.d/spoof.hosts
192.168.1.142 www.myserver.com myserver.com
```
Separate machine on LAN shows that spoofed mapping should work:
```
dig +short @192.168.1.142 myserver.com
>> 192.168.1.142
```
My dnsmasq.conf:
```
server=127.0.0.1
listen-address=127.0.0.1
listen-address=192.168.1.142
no-dhcp-interface=
no-hosts
addn-hosts=/etc/dnsmasq.d/spoof.hosts
```
My spoof.hosts:
```
192.168.1.142 www.myserver.com myserver.com
```
On the local server, I configured NGINX with resolver to look to localhost for DNS as shown here:
```
http {
access_log off;
include mime.types;
default_type html;
sendfile on;
keepalive_requests 50;
keepalive_timeout 75s;
reset_timedout_connection on;
server_tokens off;
server {
listen 8080 default_server;
resolver 127.0.0.1 valid=10s;
location / {
return 302 http://myserver.com/;
}
}
server {
listen 80;
server_name *.myserver.com;
// Various Endpoints
}
}
```
The problem is that when I visit my local machine 192.168.1.131:8080, it redirects to my **actual** internet facing machine - the **real** domain name on the internet.
I want it to redirect to the local spoofed DNS. What am I doing wrong? How can I accomplish this? Thank you.
UPDATE: I've tried this as well but no luck:
```
http {
access_log off;
include mime.types;
default_type html;
sendfile on;
keepalive_requests 50;
keepalive_timeout 75s;
reset_timedout_connection on;
server_tokens off;
server {
listen 80 default_server;
server_name _;
resolver 127.0.0.1;
return 301 https://myserver.com/$request_uri;
}
server {
listen 443;
server_name *.myserver.com;
ssl on;
ssl_certificate /etc/nginx/ssl/1e17e6d8f94cc4ee.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
...
}
}
``` | 2018/02/01 | [
"https://unix.stackexchange.com/questions/421206",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/63801/"
]
| When nginx sends a redirect, it simply tells the client to visit the new URL. So now on the client the new hostname is resolved, and as that client is not using the spoofing DNS server, it goes to the real host.
Perhaps you want to use nginx in proxy mode, so that nginx is fetching the content from the backend and relaying that on to the client. | Your nginx won't need to resolve anything at all when it sends the redirect - it literally just tells the clients "go to <https://myserver.com> instead".
Then the client, on its own, uses the DNS servers it has been configured with, to look up the IP address of myserver.com.
You need to make sure the client will use 192.168.1.142 and nothing else as its DNS server. |
421,206 | I have a Linux VPS serving data on the internet that has a legitimate Domain name and SSL Certificate ( from GoDaddy.com ). I will refere to this server as "**www.myserver.com**". I also have a local Linux machine ( on my own LAN ) that I want to use to DNS spoof my internet facing Domain name ( www.myserver.com ) to it's own NGINX webserver running on that local machine.
I setup DNSMasq on the local machine to spoof that domain to it's local 192.x address and I verified from another machine on the LAN that dig reports the local address.
Local server dnsmaq spoof mapping:
```
cat /etc/dnsmasq.d/spoof.hosts
192.168.1.142 www.myserver.com myserver.com
```
Separate machine on LAN shows that spoofed mapping should work:
```
dig +short @192.168.1.142 myserver.com
>> 192.168.1.142
```
My dnsmasq.conf:
```
server=127.0.0.1
listen-address=127.0.0.1
listen-address=192.168.1.142
no-dhcp-interface=
no-hosts
addn-hosts=/etc/dnsmasq.d/spoof.hosts
```
My spoof.hosts:
```
192.168.1.142 www.myserver.com myserver.com
```
On the local server, I configured NGINX with resolver to look to localhost for DNS as shown here:
```
http {
access_log off;
include mime.types;
default_type html;
sendfile on;
keepalive_requests 50;
keepalive_timeout 75s;
reset_timedout_connection on;
server_tokens off;
server {
listen 8080 default_server;
resolver 127.0.0.1 valid=10s;
location / {
return 302 http://myserver.com/;
}
}
server {
listen 80;
server_name *.myserver.com;
// Various Endpoints
}
}
```
The problem is that when I visit my local machine 192.168.1.131:8080, it redirects to my **actual** internet facing machine - the **real** domain name on the internet.
I want it to redirect to the local spoofed DNS. What am I doing wrong? How can I accomplish this? Thank you.
UPDATE: I've tried this as well but no luck:
```
http {
access_log off;
include mime.types;
default_type html;
sendfile on;
keepalive_requests 50;
keepalive_timeout 75s;
reset_timedout_connection on;
server_tokens off;
server {
listen 80 default_server;
server_name _;
resolver 127.0.0.1;
return 301 https://myserver.com/$request_uri;
}
server {
listen 443;
server_name *.myserver.com;
ssl on;
ssl_certificate /etc/nginx/ssl/1e17e6d8f94cc4ee.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
...
}
}
``` | 2018/02/01 | [
"https://unix.stackexchange.com/questions/421206",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/63801/"
]
| When nginx sends a redirect, it simply tells the client to visit the new URL. So now on the client the new hostname is resolved, and as that client is not using the spoofing DNS server, it goes to the real host.
Perhaps you want to use nginx in proxy mode, so that nginx is fetching the content from the backend and relaying that on to the client. | If I correctly understand, you have two machines of interest on your LAN: Let's call them 142 (which stands for 192.168.2.142) and 131 (standing for 192.168.1.131).
If I still correctly understand, when you connect from 131 to 131:8080 you want to be forwarded to 142, spoofing www.myserver.com.
If that is the case, you need to have DNSMasq running on 131, not on 142.
What you need to verify is that
```
$ dig +short myserver.com # running on 131, no @parameter
>> 192.168.1.142
```
If, on the other hand, you have more machines that when connecting to 131:8080 should be redirected to 142 spoofing www.myserver.com, you need all those machines to use your instance of DNSMasq as their default DNS server. |
46,346,064 | I'm trying to define a regex in php to extract words but i didn't succeed...
My string is always in this format: "toto=on test=on azerty=on gogo=on"
what I would like to do is to get in an array the values toto, test,azerty and gogo. Can someone help ?
that's what i tried so far : `/([^\s]|[w]*?=)/` | 2017/09/21 | [
"https://Stackoverflow.com/questions/46346064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5555681/"
]
| It's simple
```
preg_match_all("/(\w*)=/", "toto=on test=on azerty=on gogo=on", $output_array)[1];
```
It will get all word before "=", the parentheses is for defining a group and put in key "1" , "\w" is for a letter and "\*" is for "many"
or You can improve that and use like that
```
preg_match_all("/(\w*)=on/", "toto=on test=on azerty=on gogo=on", $output_array)[1];
```
So will get only parameters "on", if you have "toto=on test=on azerty=on gogo=on toff=off", the string "toff" dont will appear
I like to use this link <http://www.phpliveregex.com/> , so you can try regex and responses in PHP | Sure! Here's a working regex: <https://regex101.com/r/IWP1Mh/1>
And here's the working code: <https://3v4l.org/QQZj5>
```
<?php
$regex = '#(?<names>\w*)=\w*#';
$string = 'toto=on test=on azerty=on gogo=on';
preg_match_all($regex, $string, $matches);
$names = $matches['names'];
var_dump($names);
```
Which outputs:
```
array(4) {
[0]=> string(4) "toto"
[1]=> string(4) "test"
[2]=> string(6) "azerty"
[3]=> string(4) "gogo"
}
``` |
46,346,064 | I'm trying to define a regex in php to extract words but i didn't succeed...
My string is always in this format: "toto=on test=on azerty=on gogo=on"
what I would like to do is to get in an array the values toto, test,azerty and gogo. Can someone help ?
that's what i tried so far : `/([^\s]|[w]*?=)/` | 2017/09/21 | [
"https://Stackoverflow.com/questions/46346064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5555681/"
]
| A different approach to this question would be this way
```
<?php
$str = "toto=on test=on azerty=on gogo=on";
$res = str_replace("=on","", $str);
$array = explode(" ", $res);
print_r($array); //Array ( [0] => toto [1] => test [2] => azerty [3] => gogo )
?>
``` | Sure! Here's a working regex: <https://regex101.com/r/IWP1Mh/1>
And here's the working code: <https://3v4l.org/QQZj5>
```
<?php
$regex = '#(?<names>\w*)=\w*#';
$string = 'toto=on test=on azerty=on gogo=on';
preg_match_all($regex, $string, $matches);
$names = $matches['names'];
var_dump($names);
```
Which outputs:
```
array(4) {
[0]=> string(4) "toto"
[1]=> string(4) "test"
[2]=> string(6) "azerty"
[3]=> string(4) "gogo"
}
``` |
46,346,064 | I'm trying to define a regex in php to extract words but i didn't succeed...
My string is always in this format: "toto=on test=on azerty=on gogo=on"
what I would like to do is to get in an array the values toto, test,azerty and gogo. Can someone help ?
that's what i tried so far : `/([^\s]|[w]*?=)/` | 2017/09/21 | [
"https://Stackoverflow.com/questions/46346064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5555681/"
]
| It's simple
```
preg_match_all("/(\w*)=/", "toto=on test=on azerty=on gogo=on", $output_array)[1];
```
It will get all word before "=", the parentheses is for defining a group and put in key "1" , "\w" is for a letter and "\*" is for "many"
or You can improve that and use like that
```
preg_match_all("/(\w*)=on/", "toto=on test=on azerty=on gogo=on", $output_array)[1];
```
So will get only parameters "on", if you have "toto=on test=on azerty=on gogo=on toff=off", the string "toff" dont will appear
I like to use this link <http://www.phpliveregex.com/> , so you can try regex and responses in PHP | A different approach to this question would be this way
```
<?php
$str = "toto=on test=on azerty=on gogo=on";
$res = str_replace("=on","", $str);
$array = explode(" ", $res);
print_r($array); //Array ( [0] => toto [1] => test [2] => azerty [3] => gogo )
?>
``` |
46,346,064 | I'm trying to define a regex in php to extract words but i didn't succeed...
My string is always in this format: "toto=on test=on azerty=on gogo=on"
what I would like to do is to get in an array the values toto, test,azerty and gogo. Can someone help ?
that's what i tried so far : `/([^\s]|[w]*?=)/` | 2017/09/21 | [
"https://Stackoverflow.com/questions/46346064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5555681/"
]
| It's simple
```
preg_match_all("/(\w*)=/", "toto=on test=on azerty=on gogo=on", $output_array)[1];
```
It will get all word before "=", the parentheses is for defining a group and put in key "1" , "\w" is for a letter and "\*" is for "many"
or You can improve that and use like that
```
preg_match_all("/(\w*)=on/", "toto=on test=on azerty=on gogo=on", $output_array)[1];
```
So will get only parameters "on", if you have "toto=on test=on azerty=on gogo=on toff=off", the string "toff" dont will appear
I like to use this link <http://www.phpliveregex.com/> , so you can try regex and responses in PHP | You can juse use `explode()`:
```
$str = 'toto=on test=on azerty=on gogo=on';
$words = array_map(function($item){ return substr($item, 0, -3); }, explode(' ', $str));
``` |
46,346,064 | I'm trying to define a regex in php to extract words but i didn't succeed...
My string is always in this format: "toto=on test=on azerty=on gogo=on"
what I would like to do is to get in an array the values toto, test,azerty and gogo. Can someone help ?
that's what i tried so far : `/([^\s]|[w]*?=)/` | 2017/09/21 | [
"https://Stackoverflow.com/questions/46346064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5555681/"
]
| A different approach to this question would be this way
```
<?php
$str = "toto=on test=on azerty=on gogo=on";
$res = str_replace("=on","", $str);
$array = explode(" ", $res);
print_r($array); //Array ( [0] => toto [1] => test [2] => azerty [3] => gogo )
?>
``` | You can juse use `explode()`:
```
$str = 'toto=on test=on azerty=on gogo=on';
$words = array_map(function($item){ return substr($item, 0, -3); }, explode(' ', $str));
``` |
2,697,571 | What is the limit of $$\lim\_{x \to \infty} \frac{\sum\_{k=0}^{x} (k+1){e^k}}{x{e^x}}\quad \text{?}$$ I think that it may go to infinity but not sure and i don't know how to solve it. | 2018/03/18 | [
"https://math.stackexchange.com/questions/2697571",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/466808/"
]
| The numerator is an arithmetico-geometric series.
\begin{align\*}
(1-e)\sum\_{k=0}^{x} (k+1){e^k}&=\sum\_{k=0}^{x} (k+1){e^k}-\sum\_{k=0}^{x} (k+1){e^{k+1}}\\
&=\sum\_{k=0}^{x} (k+1){e^k}-\sum\_{k=1}^{x+1} k{e^{k}}\\
&=\sum\_{k=0}^{x} (k+1){e^k}-\sum\_{k=0}^{x} k{e^{k}}-(x+1)e^{x+1}\\
&=\sum\_{k=0}^{x} {e^k}-(x+1)e^{x+1}\\
&=\frac{e^{x+1}-1} {e-1}-(x+1)e^{x+1}\\
\sum\_{k=0}^{x} (k+1){e^k}&=\frac{(x+1)e^{x+1}}{e-1}-\frac{e^{x+1}-1} {(e-1)^2}\\
\frac{1}{xe^x}\sum\_{k=0}^{x} (k+1){e^k}&=\frac{(x+1)e}{x(e-1)}-\frac{e-e^{-x}} {x(e-1)^2}\\
\lim\_{x\to\infty}\frac{1}{xe^x}\sum\_{k=0}^{x} (k+1){e^k}&=\frac{e}{e-1}
\end{align\*} | For $x$ a natural.
$$
\sum\_{k=0}^{x}\left(k+1\right)e^{k}=\frac{1}{\left(e-1\right)^2}\left(\left(x+1\right)e^{x+2}-\left(x+2\right)e^{x+1}+1\right)
$$
So
$$\frac{\displaystyle \sum\_{k=0}^{x}\left(k+1\right)e^{k}}{xe^x}=\frac{1}{\left(e-1\right)^2}\left(\frac{x+1}{x}e^{2}-\left(x+2\right)\frac{e}{x}+\frac{1}{xe^{x}}\right)
$$
Hence, the limit exists and
>
> $$\frac{\displaystyle \sum\_{k=0}^{x}\left(k+1\right)e^{k}}{xe^x} \underset{x \rightarrow +\infty}{\rightarrow}\frac{e^2-e}{\left(e-1\right)^2}=\frac{e}{e-1} \approx 1.58197$$
>
>
> |
5,661,101 | Is it possible to represent an unsigned character array as a string?
When I searched for it, I found out that only memset() was able to do this (But character by character).
Assuming that is not the correct way, is there a way to do the conversion?
Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters.
eg:
```
unsigned char data[N]; ...
for(i=0;i<N;i++) printf("%x",data[i]);
```
My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing.
Thanks! | 2011/04/14 | [
"https://Stackoverflow.com/questions/5661101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420157/"
]
| In C, a string is an array of `char`, terminated with a character whose value is 0.
Whether or not `char` is a signed or unsigned type is not specified by the language, you have to be explicit and use `unsigned char` or `signed char` if you really care.
It's not clear what you mean by "representing" an unsigned character array as string. It's easy enough to cast away the sign, if you want to do something like:
```
const unsigned char abc[] = { 65, 66,67, 0 }; // ASCII values for 'A', 'B', 'C'.
printf("The English alphabet starts out with '%s'\n", (const char *) abc);
```
This will work, to `printf()` there isn't much difference, it will see a pointer to an array of characters and interpret them as a string.
Of course, if you're on a system that doesn't use ASCII, there might creep in cases where doing this won't work. Again, your question isn't very clear. | An example as you've asked:
unsigned char arr [SIZE]; |
5,661,101 | Is it possible to represent an unsigned character array as a string?
When I searched for it, I found out that only memset() was able to do this (But character by character).
Assuming that is not the correct way, is there a way to do the conversion?
Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters.
eg:
```
unsigned char data[N]; ...
for(i=0;i<N;i++) printf("%x",data[i]);
```
My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing.
Thanks! | 2011/04/14 | [
"https://Stackoverflow.com/questions/5661101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420157/"
]
| So, based on your update, are you talking about trying to convert a unsigned char buffer into a hexadecimal interpretation, something like this:
```
#define bufferSize 10
int main() {
unsigned char buffer[bufferSize]={1,2,3,4,5,6,7,8,9,10};
char converted[bufferSize*2 + 1];
int i;
for(i=0;i<bufferSize;i++) {
sprintf(&converted[i*2], "%02X", buffer[i]);
/* equivalent using snprintf, notice len field keeps reducing
with each pass, to prevent overruns
snprintf(&converted[i*2], sizeof(converted)-(i*2),"%02X", buffer[i]);
*/
}
printf("%s\n", converted);
return 0;
}
```
Which outputs:
```
0102030405060708090A
``` | In C, a string is an array of `char`, terminated with a character whose value is 0.
Whether or not `char` is a signed or unsigned type is not specified by the language, you have to be explicit and use `unsigned char` or `signed char` if you really care.
It's not clear what you mean by "representing" an unsigned character array as string. It's easy enough to cast away the sign, if you want to do something like:
```
const unsigned char abc[] = { 65, 66,67, 0 }; // ASCII values for 'A', 'B', 'C'.
printf("The English alphabet starts out with '%s'\n", (const char *) abc);
```
This will work, to `printf()` there isn't much difference, it will see a pointer to an array of characters and interpret them as a string.
Of course, if you're on a system that doesn't use ASCII, there might creep in cases where doing this won't work. Again, your question isn't very clear. |
5,661,101 | Is it possible to represent an unsigned character array as a string?
When I searched for it, I found out that only memset() was able to do this (But character by character).
Assuming that is not the correct way, is there a way to do the conversion?
Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters.
eg:
```
unsigned char data[N]; ...
for(i=0;i<N;i++) printf("%x",data[i]);
```
My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing.
Thanks! | 2011/04/14 | [
"https://Stackoverflow.com/questions/5661101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420157/"
]
| In C, a string is an array of `char`, terminated with a character whose value is 0.
Whether or not `char` is a signed or unsigned type is not specified by the language, you have to be explicit and use `unsigned char` or `signed char` if you really care.
It's not clear what you mean by "representing" an unsigned character array as string. It's easy enough to cast away the sign, if you want to do something like:
```
const unsigned char abc[] = { 65, 66,67, 0 }; // ASCII values for 'A', 'B', 'C'.
printf("The English alphabet starts out with '%s'\n", (const char *) abc);
```
This will work, to `printf()` there isn't much difference, it will see a pointer to an array of characters and interpret them as a string.
Of course, if you're on a system that doesn't use ASCII, there might creep in cases where doing this won't work. Again, your question isn't very clear. | I successfully use this to convert unsigned char array to std:string
```
unsigned char array[128];
std::stringstream buffer;
for (int i = 0; i < 128; i++)
{
buffer << std::hex << std::setfill('0');
buffer << std::setw(2) << static_cast<unsigned>(array[i]);
}
std::string hexString = buffer.str();
``` |
5,661,101 | Is it possible to represent an unsigned character array as a string?
When I searched for it, I found out that only memset() was able to do this (But character by character).
Assuming that is not the correct way, is there a way to do the conversion?
Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters.
eg:
```
unsigned char data[N]; ...
for(i=0;i<N;i++) printf("%x",data[i]);
```
My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing.
Thanks! | 2011/04/14 | [
"https://Stackoverflow.com/questions/5661101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420157/"
]
| Well a string in C is nothing else than a few chars one after another. If they are unsigned or signed is not much of a problem, you can easily cast them.
So to get a string out of a unsigned char array all you have to do is to make sure that the last byte is a terminating byte '\0' and then cast this array to char \* (or copy it into a array of char) | An example as you've asked:
unsigned char arr [SIZE]; |
5,661,101 | Is it possible to represent an unsigned character array as a string?
When I searched for it, I found out that only memset() was able to do this (But character by character).
Assuming that is not the correct way, is there a way to do the conversion?
Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters.
eg:
```
unsigned char data[N]; ...
for(i=0;i<N;i++) printf("%x",data[i]);
```
My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing.
Thanks! | 2011/04/14 | [
"https://Stackoverflow.com/questions/5661101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420157/"
]
| So, based on your update, are you talking about trying to convert a unsigned char buffer into a hexadecimal interpretation, something like this:
```
#define bufferSize 10
int main() {
unsigned char buffer[bufferSize]={1,2,3,4,5,6,7,8,9,10};
char converted[bufferSize*2 + 1];
int i;
for(i=0;i<bufferSize;i++) {
sprintf(&converted[i*2], "%02X", buffer[i]);
/* equivalent using snprintf, notice len field keeps reducing
with each pass, to prevent overruns
snprintf(&converted[i*2], sizeof(converted)-(i*2),"%02X", buffer[i]);
*/
}
printf("%s\n", converted);
return 0;
}
```
Which outputs:
```
0102030405060708090A
``` | Well a string in C is nothing else than a few chars one after another. If they are unsigned or signed is not much of a problem, you can easily cast them.
So to get a string out of a unsigned char array all you have to do is to make sure that the last byte is a terminating byte '\0' and then cast this array to char \* (or copy it into a array of char) |
5,661,101 | Is it possible to represent an unsigned character array as a string?
When I searched for it, I found out that only memset() was able to do this (But character by character).
Assuming that is not the correct way, is there a way to do the conversion?
Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters.
eg:
```
unsigned char data[N]; ...
for(i=0;i<N;i++) printf("%x",data[i]);
```
My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing.
Thanks! | 2011/04/14 | [
"https://Stackoverflow.com/questions/5661101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420157/"
]
| Well a string in C is nothing else than a few chars one after another. If they are unsigned or signed is not much of a problem, you can easily cast them.
So to get a string out of a unsigned char array all you have to do is to make sure that the last byte is a terminating byte '\0' and then cast this array to char \* (or copy it into a array of char) | I successfully use this to convert unsigned char array to std:string
```
unsigned char array[128];
std::stringstream buffer;
for (int i = 0; i < 128; i++)
{
buffer << std::hex << std::setfill('0');
buffer << std::setw(2) << static_cast<unsigned>(array[i]);
}
std::string hexString = buffer.str();
``` |
5,661,101 | Is it possible to represent an unsigned character array as a string?
When I searched for it, I found out that only memset() was able to do this (But character by character).
Assuming that is not the correct way, is there a way to do the conversion?
Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters.
eg:
```
unsigned char data[N]; ...
for(i=0;i<N;i++) printf("%x",data[i]);
```
My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing.
Thanks! | 2011/04/14 | [
"https://Stackoverflow.com/questions/5661101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420157/"
]
| So, based on your update, are you talking about trying to convert a unsigned char buffer into a hexadecimal interpretation, something like this:
```
#define bufferSize 10
int main() {
unsigned char buffer[bufferSize]={1,2,3,4,5,6,7,8,9,10};
char converted[bufferSize*2 + 1];
int i;
for(i=0;i<bufferSize;i++) {
sprintf(&converted[i*2], "%02X", buffer[i]);
/* equivalent using snprintf, notice len field keeps reducing
with each pass, to prevent overruns
snprintf(&converted[i*2], sizeof(converted)-(i*2),"%02X", buffer[i]);
*/
}
printf("%s\n", converted);
return 0;
}
```
Which outputs:
```
0102030405060708090A
``` | An example as you've asked:
unsigned char arr [SIZE]; |
5,661,101 | Is it possible to represent an unsigned character array as a string?
When I searched for it, I found out that only memset() was able to do this (But character by character).
Assuming that is not the correct way, is there a way to do the conversion?
Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters.
eg:
```
unsigned char data[N]; ...
for(i=0;i<N;i++) printf("%x",data[i]);
```
My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing.
Thanks! | 2011/04/14 | [
"https://Stackoverflow.com/questions/5661101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420157/"
]
| I successfully use this to convert unsigned char array to std:string
```
unsigned char array[128];
std::stringstream buffer;
for (int i = 0; i < 128; i++)
{
buffer << std::hex << std::setfill('0');
buffer << std::setw(2) << static_cast<unsigned>(array[i]);
}
std::string hexString = buffer.str();
``` | An example as you've asked:
unsigned char arr [SIZE]; |
5,661,101 | Is it possible to represent an unsigned character array as a string?
When I searched for it, I found out that only memset() was able to do this (But character by character).
Assuming that is not the correct way, is there a way to do the conversion?
Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters.
eg:
```
unsigned char data[N]; ...
for(i=0;i<N;i++) printf("%x",data[i]);
```
My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing.
Thanks! | 2011/04/14 | [
"https://Stackoverflow.com/questions/5661101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420157/"
]
| So, based on your update, are you talking about trying to convert a unsigned char buffer into a hexadecimal interpretation, something like this:
```
#define bufferSize 10
int main() {
unsigned char buffer[bufferSize]={1,2,3,4,5,6,7,8,9,10};
char converted[bufferSize*2 + 1];
int i;
for(i=0;i<bufferSize;i++) {
sprintf(&converted[i*2], "%02X", buffer[i]);
/* equivalent using snprintf, notice len field keeps reducing
with each pass, to prevent overruns
snprintf(&converted[i*2], sizeof(converted)-(i*2),"%02X", buffer[i]);
*/
}
printf("%s\n", converted);
return 0;
}
```
Which outputs:
```
0102030405060708090A
``` | I successfully use this to convert unsigned char array to std:string
```
unsigned char array[128];
std::stringstream buffer;
for (int i = 0; i < 128; i++)
{
buffer << std::hex << std::setfill('0');
buffer << std::setw(2) << static_cast<unsigned>(array[i]);
}
std::string hexString = buffer.str();
``` |
709,855 | Prove that if $H$ is a subgroup of index $2$ in a finite group $G$, then $gH = Hg \; \forall \; g \in G$.
I know that $H$ itself is one coset of the subgroup and the other is the compliment of the subgroup, but I don't really understand why the second coset is the compliment. I know that the union of the cosets must be $G$, but how do we know that we can't say, for example, $2H \cup H \equiv G$? Why do we **know** for sure that $H'\cup H$ is $G$?
I also know that the number of left and right cosets are identical. | 2014/03/12 | [
"https://math.stackexchange.com/questions/709855",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/80327/"
]
| Remember, Langrange's theorem? There was an equivalence relation $a \sim b$ if $a^{-1}b \in H$
So $G\backslash H$ are the equivalence classes induced by $a \sim b$ if $a^{-1}b \in H$ In other words, the cosets represent the different equivalence classes induced by this equivalence relation. What do we know from equivalence classes? They $partition$ $G$, so if $aH$ and $bH$ are two different cosets then $aH \cap bH = \emptyset$ Therfore, if H has index 2 that means that $G\backslash H$ has two cosets. One coset you know is H and the other coset must have $a \in G$ such that $a \notin H$ which is just $H'$ These must also be the right cosets, hence $gH =Hg $ $\forall g \in G$ | As you already know the number of left cosets is equal to the number of right ones, just take into account that
$$aH=H\iff a\in H$$
$$Ha=H\iff a\in H$$ |
3,569,212 | >
> Count the number of arrangements of the $10$ letters ABCDEFGHIJ in which none of the patterns ABE, BED, or HID occur.
>
>
>
I thought that the answer would be $\_{10}P\_{10} - (\_{10}P\_{3} + \_{10}P\_{3} + \_{10}P\_{3} - \_{10}P\_{2}$), since we have $\_{10}P\_{10}$ total arrangements, and $\_{10}P\_{3}$ arrangements for ABE, BED, and HID. But we subtracted $BE$ twice, so we need to add it back in: $\_{10}P\_{2}$.
Please tell me what is wrong with my reasoning! | 2020/03/04 | [
"https://math.stackexchange.com/questions/3569212",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/742306/"
]
| $\_{10}P\_3$ is not the number of arrangements where $ABE$ occurs. You have $7!$ ways to put the other letters in order and $8$ places to put the unit $ABE$ so $8!$ ways to put all the letters in order including $ABE$. Alternately, you can group $ABE$ into one letter, have $8$ letters, which again gives $8!$ orders.
Your double subtraction is combinations with $ABED$ and combinations with both $ABE$ and $HID$, so you need to add those back in once. | Since $ABE$ and $HID$ are disjoint, all Permutations where both patterns occur are subtracted twice. |
3,569,212 | >
> Count the number of arrangements of the $10$ letters ABCDEFGHIJ in which none of the patterns ABE, BED, or HID occur.
>
>
>
I thought that the answer would be $\_{10}P\_{10} - (\_{10}P\_{3} + \_{10}P\_{3} + \_{10}P\_{3} - \_{10}P\_{2}$), since we have $\_{10}P\_{10}$ total arrangements, and $\_{10}P\_{3}$ arrangements for ABE, BED, and HID. But we subtracted $BE$ twice, so we need to add it back in: $\_{10}P\_{2}$.
Please tell me what is wrong with my reasoning! | 2020/03/04 | [
"https://math.stackexchange.com/questions/3569212",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/742306/"
]
| There are $10!$ permutations of the ten distinct letters. From these, we must subtract those arrangements in which the substrings ABE, BED, or HID appear.
*Arrangements with a prohibited substring*: We count arrangements in which ABE appears. We have eight objects to arrange: ABE, C, D, F, G, H, I, J. Since the objects are distinct, they can be arranged in $8!$ ways.
By symmetry, there are $8!$ arrangements in which BED appears and $8!$ arrangements in which HID appears.
Hence, there are $3 \cdot 8!$ arrangements with a prohibited substring.
However, if we subtract this amount from the total, we will have subtracted each arrangement in which two prohibited substrings appear twice, once for each way we could designate one of those substrings as the prohibited one. We only want to subtract such arrangements once, so we must add them back.
*Arrangements with two prohibited substrings*: Since it is not possible for a permutation of the letters A, B, C, D, E, F, G, H, I, J to contain both BED and HID, this can occur in two ways. Either both ABE and BED appear in the arrangement or both ABE and HID appear in the arrangement.
Substrings ABE and BED both appear in the arrangement: This can only occur if the arrangement contains the substring ABED. Then we have seven objects to arrange: ABED, C, F, G, H, I, J. Since the objects are distinct, they can be arranged in $7!$ ways.
Substrings ABE and HID both appear in the arrangement: We have six objects to arrange: ABE, HID, C, F, G, H, I, J. Since the objects are distinct, they can be arranged in $6!$ ways.
*Arrangements with three prohibited substrings*: Since BED and HID cannot both appear in an arrangement of the letters A, B, C, D, E, F, G, H, I, J, there are no arrangements in which ABE, BED, and HID all appear.
Therefore, by the [Inclusion-Exclusion Principle](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle), the number of arrangements of the letters A, B, C, D, E, F, G, H, I, J in which none of the substrings ABE, BED, and HID appear is
$$10! - 3 \cdot 8! + 7! + 6!$$ | Since $ABE$ and $HID$ are disjoint, all Permutations where both patterns occur are subtracted twice. |
3,569,212 | >
> Count the number of arrangements of the $10$ letters ABCDEFGHIJ in which none of the patterns ABE, BED, or HID occur.
>
>
>
I thought that the answer would be $\_{10}P\_{10} - (\_{10}P\_{3} + \_{10}P\_{3} + \_{10}P\_{3} - \_{10}P\_{2}$), since we have $\_{10}P\_{10}$ total arrangements, and $\_{10}P\_{3}$ arrangements for ABE, BED, and HID. But we subtracted $BE$ twice, so we need to add it back in: $\_{10}P\_{2}$.
Please tell me what is wrong with my reasoning! | 2020/03/04 | [
"https://math.stackexchange.com/questions/3569212",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/742306/"
]
| $\_{10}P\_3$ is not the number of arrangements where $ABE$ occurs. You have $7!$ ways to put the other letters in order and $8$ places to put the unit $ABE$ so $8!$ ways to put all the letters in order including $ABE$. Alternately, you can group $ABE$ into one letter, have $8$ letters, which again gives $8!$ orders.
Your double subtraction is combinations with $ABED$ and combinations with both $ABE$ and $HID$, so you need to add those back in once. | If you're just interested in the result: Brute force tells me $3513600$.
But let's figure this out. There are $10!$ permutations in total. We have to subtract those with $ABE$. There are $8!$ of them (just treat $ABE$ as a single letter). Likewise, we have $8!$ for each of the other two three letter patterns. That leaves us with $10!-3\cdot8!$. Now we have subtracted patterns like $\ldots{}ABE\ldots{}HID\ldots$ twice. How many of them are there? The number of letters left is $4$ with $4!$ permutations of them and exactly two out of 5 spots (the spots before between and after the four letters) where the two patterns are inserted. Assume the first pattern goes into the first slot. Then the second one can also go there or into the second or third and so on. If the first pattern goes into the second slot the second one can only go into the second or third and so on. This means there are $\sum\_{i=1}^{5}i=15$ possibilities. As $ABE$ can be the first or the second pattern, we multiply by $2$ which gives us a total of $4!\cdot15\cdot2=720$ permutations with both $ABE$ and $HID$ in them. Now, $HID$ and $BED$ can obviously never occur simultaneously. But $ABE$ and $BED$ can. How often does that happen. Just treat $ABED$ as one letter then there are $7!$ of them. They also need to be put back in. We end up with $$10!-3\cdot8!+4!\cdot15\cdot2+7!=3513600$$ |
3,569,212 | >
> Count the number of arrangements of the $10$ letters ABCDEFGHIJ in which none of the patterns ABE, BED, or HID occur.
>
>
>
I thought that the answer would be $\_{10}P\_{10} - (\_{10}P\_{3} + \_{10}P\_{3} + \_{10}P\_{3} - \_{10}P\_{2}$), since we have $\_{10}P\_{10}$ total arrangements, and $\_{10}P\_{3}$ arrangements for ABE, BED, and HID. But we subtracted $BE$ twice, so we need to add it back in: $\_{10}P\_{2}$.
Please tell me what is wrong with my reasoning! | 2020/03/04 | [
"https://math.stackexchange.com/questions/3569212",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/742306/"
]
| There are $10!$ permutations of the ten distinct letters. From these, we must subtract those arrangements in which the substrings ABE, BED, or HID appear.
*Arrangements with a prohibited substring*: We count arrangements in which ABE appears. We have eight objects to arrange: ABE, C, D, F, G, H, I, J. Since the objects are distinct, they can be arranged in $8!$ ways.
By symmetry, there are $8!$ arrangements in which BED appears and $8!$ arrangements in which HID appears.
Hence, there are $3 \cdot 8!$ arrangements with a prohibited substring.
However, if we subtract this amount from the total, we will have subtracted each arrangement in which two prohibited substrings appear twice, once for each way we could designate one of those substrings as the prohibited one. We only want to subtract such arrangements once, so we must add them back.
*Arrangements with two prohibited substrings*: Since it is not possible for a permutation of the letters A, B, C, D, E, F, G, H, I, J to contain both BED and HID, this can occur in two ways. Either both ABE and BED appear in the arrangement or both ABE and HID appear in the arrangement.
Substrings ABE and BED both appear in the arrangement: This can only occur if the arrangement contains the substring ABED. Then we have seven objects to arrange: ABED, C, F, G, H, I, J. Since the objects are distinct, they can be arranged in $7!$ ways.
Substrings ABE and HID both appear in the arrangement: We have six objects to arrange: ABE, HID, C, F, G, H, I, J. Since the objects are distinct, they can be arranged in $6!$ ways.
*Arrangements with three prohibited substrings*: Since BED and HID cannot both appear in an arrangement of the letters A, B, C, D, E, F, G, H, I, J, there are no arrangements in which ABE, BED, and HID all appear.
Therefore, by the [Inclusion-Exclusion Principle](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle), the number of arrangements of the letters A, B, C, D, E, F, G, H, I, J in which none of the substrings ABE, BED, and HID appear is
$$10! - 3 \cdot 8! + 7! + 6!$$ | $\_{10}P\_3$ is not the number of arrangements where $ABE$ occurs. You have $7!$ ways to put the other letters in order and $8$ places to put the unit $ABE$ so $8!$ ways to put all the letters in order including $ABE$. Alternately, you can group $ABE$ into one letter, have $8$ letters, which again gives $8!$ orders.
Your double subtraction is combinations with $ABED$ and combinations with both $ABE$ and $HID$, so you need to add those back in once. |
3,569,212 | >
> Count the number of arrangements of the $10$ letters ABCDEFGHIJ in which none of the patterns ABE, BED, or HID occur.
>
>
>
I thought that the answer would be $\_{10}P\_{10} - (\_{10}P\_{3} + \_{10}P\_{3} + \_{10}P\_{3} - \_{10}P\_{2}$), since we have $\_{10}P\_{10}$ total arrangements, and $\_{10}P\_{3}$ arrangements for ABE, BED, and HID. But we subtracted $BE$ twice, so we need to add it back in: $\_{10}P\_{2}$.
Please tell me what is wrong with my reasoning! | 2020/03/04 | [
"https://math.stackexchange.com/questions/3569212",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/742306/"
]
| There are $10!$ permutations of the ten distinct letters. From these, we must subtract those arrangements in which the substrings ABE, BED, or HID appear.
*Arrangements with a prohibited substring*: We count arrangements in which ABE appears. We have eight objects to arrange: ABE, C, D, F, G, H, I, J. Since the objects are distinct, they can be arranged in $8!$ ways.
By symmetry, there are $8!$ arrangements in which BED appears and $8!$ arrangements in which HID appears.
Hence, there are $3 \cdot 8!$ arrangements with a prohibited substring.
However, if we subtract this amount from the total, we will have subtracted each arrangement in which two prohibited substrings appear twice, once for each way we could designate one of those substrings as the prohibited one. We only want to subtract such arrangements once, so we must add them back.
*Arrangements with two prohibited substrings*: Since it is not possible for a permutation of the letters A, B, C, D, E, F, G, H, I, J to contain both BED and HID, this can occur in two ways. Either both ABE and BED appear in the arrangement or both ABE and HID appear in the arrangement.
Substrings ABE and BED both appear in the arrangement: This can only occur if the arrangement contains the substring ABED. Then we have seven objects to arrange: ABED, C, F, G, H, I, J. Since the objects are distinct, they can be arranged in $7!$ ways.
Substrings ABE and HID both appear in the arrangement: We have six objects to arrange: ABE, HID, C, F, G, H, I, J. Since the objects are distinct, they can be arranged in $6!$ ways.
*Arrangements with three prohibited substrings*: Since BED and HID cannot both appear in an arrangement of the letters A, B, C, D, E, F, G, H, I, J, there are no arrangements in which ABE, BED, and HID all appear.
Therefore, by the [Inclusion-Exclusion Principle](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle), the number of arrangements of the letters A, B, C, D, E, F, G, H, I, J in which none of the substrings ABE, BED, and HID appear is
$$10! - 3 \cdot 8! + 7! + 6!$$ | If you're just interested in the result: Brute force tells me $3513600$.
But let's figure this out. There are $10!$ permutations in total. We have to subtract those with $ABE$. There are $8!$ of them (just treat $ABE$ as a single letter). Likewise, we have $8!$ for each of the other two three letter patterns. That leaves us with $10!-3\cdot8!$. Now we have subtracted patterns like $\ldots{}ABE\ldots{}HID\ldots$ twice. How many of them are there? The number of letters left is $4$ with $4!$ permutations of them and exactly two out of 5 spots (the spots before between and after the four letters) where the two patterns are inserted. Assume the first pattern goes into the first slot. Then the second one can also go there or into the second or third and so on. If the first pattern goes into the second slot the second one can only go into the second or third and so on. This means there are $\sum\_{i=1}^{5}i=15$ possibilities. As $ABE$ can be the first or the second pattern, we multiply by $2$ which gives us a total of $4!\cdot15\cdot2=720$ permutations with both $ABE$ and $HID$ in them. Now, $HID$ and $BED$ can obviously never occur simultaneously. But $ABE$ and $BED$ can. How often does that happen. Just treat $ABED$ as one letter then there are $7!$ of them. They also need to be put back in. We end up with $$10!-3\cdot8!+4!\cdot15\cdot2+7!=3513600$$ |
31,571,321 | The question's prompt is:
>
> Write a method that takes an array of numbers. If a pair of numbers in the array sums to zero, return the positions of those two numbers. If no pair of numbers sums to zero, return `nil`.
>
>
>
I'm not sure how to approach this problem and what would be the simplest way. Would this involve the .index method?
```
def two_sum(nums)
end
two_sum([1,3,5,-3])
``` | 2015/07/22 | [
"https://Stackoverflow.com/questions/31571321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5042162/"
]
| As with a lot of things in Ruby, there are a couple different ways of doing this. The "classic" approach to this problem would be to use two nested loops:
```
def two_sum(nums)
for i1 in 0...nums.length
for i2 in i1...nums.length
# Inside this loop, nums[i1] represents one number in the array
# and nums[i2] represents a different number.
#
# If we find that the sum of these numbers is zero...
if nums[i1] + nums[i2] == 0
# Then we have our answer
return i1, i2
end
end
end
# At this point we've checked every possible combination and haven't
# found an answer, so a pair of numbers that sum to zero in that array
# must not exist. Return nil.
nil
end
```
The other approach uses Ruby magic to do the same thing in a somewhat more expressive way:
```
def two_sum(nums)
result_pair = nums.each_with_index.to_a.combination(2).find{|n1, n2| n1.first + n2.first == 0}
result_pair && result_pair.map(&:last)
end
```
The breakdown here is a bit more complex. If you'd like to understand it, I recommend looking at the documentation for these methods on [`Array`](http://ruby-doc.org/core/Array.html) and [`Enumerable`](http://ruby-doc.org/core/Enumerable.html). | Here is another way to do this:
```
def two_sum(nums)
seen = {}
nums.each_with_index do |n, i|
return seen[-1*n], i if seen.key?(-1*n)
seen[n] = i
end
nil
end
```
It's faster that the above (you do it in one pass) so O(n).
It does use O(n) additional space compared to the naive approach that checks each element against each element (but that one's O(n^2) |
31,571,321 | The question's prompt is:
>
> Write a method that takes an array of numbers. If a pair of numbers in the array sums to zero, return the positions of those two numbers. If no pair of numbers sums to zero, return `nil`.
>
>
>
I'm not sure how to approach this problem and what would be the simplest way. Would this involve the .index method?
```
def two_sum(nums)
end
two_sum([1,3,5,-3])
``` | 2015/07/22 | [
"https://Stackoverflow.com/questions/31571321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5042162/"
]
| As with a lot of things in Ruby, there are a couple different ways of doing this. The "classic" approach to this problem would be to use two nested loops:
```
def two_sum(nums)
for i1 in 0...nums.length
for i2 in i1...nums.length
# Inside this loop, nums[i1] represents one number in the array
# and nums[i2] represents a different number.
#
# If we find that the sum of these numbers is zero...
if nums[i1] + nums[i2] == 0
# Then we have our answer
return i1, i2
end
end
end
# At this point we've checked every possible combination and haven't
# found an answer, so a pair of numbers that sum to zero in that array
# must not exist. Return nil.
nil
end
```
The other approach uses Ruby magic to do the same thing in a somewhat more expressive way:
```
def two_sum(nums)
result_pair = nums.each_with_index.to_a.combination(2).find{|n1, n2| n1.first + n2.first == 0}
result_pair && result_pair.map(&:last)
end
```
The breakdown here is a bit more complex. If you'd like to understand it, I recommend looking at the documentation for these methods on [`Array`](http://ruby-doc.org/core/Array.html) and [`Enumerable`](http://ruby-doc.org/core/Enumerable.html). | This returns offsets for all pairs of values that sum to zero. The return value is not unique, however. If, for example, `a = [1,1,1,-1,-1]`, pairs summing to zero might be at offsets `[[0,3],[1,4]]` or `[[1,3],[2,4]]` or other values.
**Code**
```
def match_zero_sums(arr)
h = arr.each_with_index.group_by(&:first)
h.keys.select { |k| k >= 0 }.each_with_object([]) do |k,a|
while (k==0 && h[k].size > 1) || (k>0 && h[k].any? && h[-k].any?)
a << [h[k].shift.last, h[-k].shift.last]
end if h.key?(-k)
end
end
```
**Example**
```
arr = [2,3,0,0,-2,-3,4,-3,0,3]
match_zero_sums(arr)
#=> [[0, 4], [1, 5], [9, 7], [2, 3]]
```
**Explanation**
For `arr` in the example:
```
enum0 = arr.each_with_index
#=> #<Enumerator: [2, 3, 0, 0, -2, -3, 4, -3, 0, 3]:each_with_index>
h = enum0.group_by(&:first)
#=> { 2=>[[2, 0]], 3=>[[3, 1], [3, 9]], 0=>[[0, 2], [0, 3], [0, 8]],
# -2=>[[-2, 4]], -3=>[[-3, 5], [-3, 7]], 4=>[[4, 6]]}
non_neg_keys = h.keys.select { |k| k >= 0 }
#=> [2, 3, 0, 4]
enum1 = non_neg_keys.each_with_object([])
#=> #<Enumerator: [2, 3, 0, 4]:each_with_object([])>
k,a = enum1.next
#=> [2, []]
k #=> 2
a #=> []
h.key?(-k)
#=> h.key?(-2) => true
```
so execute the `while` loop:
```
k==0 && h[k].size > 1
#=> 2==0 && h[2].size > 1
#=> false && true => false
k>0 && h[k].any? && h[-k].any?
#=> 2>0 && h[2].any? && h[-2].any?
#=> true && true && true => true
false || true #=> true
```
so compute:
```
a << [h[k].shift.last, h[-k].shift.last]
#=> a << [h[2].shift.last, h[-2].shift.last]
#=> a << [[2,0].last, [-2,4].last]
#=> a << [0,4]
```
so now:
```
a #=> [[0,4]]
```
and
```
h #=> { 2=>[], 3=>[[3, 1], [3, 9]], 0=>[[0, 2], [0, 3], [0, 8]],
# -2=>[], -3=>[[-3, 5], [-3, 7]], 4=>[[4, 6]]}
```
The remaining calculations are similar. |
31,571,321 | The question's prompt is:
>
> Write a method that takes an array of numbers. If a pair of numbers in the array sums to zero, return the positions of those two numbers. If no pair of numbers sums to zero, return `nil`.
>
>
>
I'm not sure how to approach this problem and what would be the simplest way. Would this involve the .index method?
```
def two_sum(nums)
end
two_sum([1,3,5,-3])
``` | 2015/07/22 | [
"https://Stackoverflow.com/questions/31571321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5042162/"
]
| As with a lot of things in Ruby, there are a couple different ways of doing this. The "classic" approach to this problem would be to use two nested loops:
```
def two_sum(nums)
for i1 in 0...nums.length
for i2 in i1...nums.length
# Inside this loop, nums[i1] represents one number in the array
# and nums[i2] represents a different number.
#
# If we find that the sum of these numbers is zero...
if nums[i1] + nums[i2] == 0
# Then we have our answer
return i1, i2
end
end
end
# At this point we've checked every possible combination and haven't
# found an answer, so a pair of numbers that sum to zero in that array
# must not exist. Return nil.
nil
end
```
The other approach uses Ruby magic to do the same thing in a somewhat more expressive way:
```
def two_sum(nums)
result_pair = nums.each_with_index.to_a.combination(2).find{|n1, n2| n1.first + n2.first == 0}
result_pair && result_pair.map(&:last)
end
```
The breakdown here is a bit more complex. If you'd like to understand it, I recommend looking at the documentation for these methods on [`Array`](http://ruby-doc.org/core/Array.html) and [`Enumerable`](http://ruby-doc.org/core/Enumerable.html). | As always, there are usually many ways to solve a problem, especially with Ruby. If you had come from another language like Java or Python, there is a great chance you might not be already familiar with the `each_with_index` or `each.with_index` methods. Without over complicating the solution, just break the problem down into two separate while loops, and return the indexes of the pair that equates to zero if it exists. Ruby provides many methods to make life much easier, but without knowing the majority of them, you'll still be able to solve a plethora of problems with a solid foundation of the basics of programming.
```
def two_sum(nums)
i = 0
while i < nums.length
j = 0
while j < nums.length
if nums[i] + nums[j] == 0
return i, j
end
j += 1
end
i += 1
end
return nil
end`
``` |
64,576,412 | To preface, I have reviewed the post [here](https://stackoverflow.com/questions/52908923/check-if-asset-exist-in-flutter), but am still having trouble.
I am building a container that is decorated with an image, only if that image exists in the assets/images/ folder. If it does not exist, the container is decorated with a default image instead.
The image path is formatted string using a variable, image\_id, that assumes a String response from an API.
Here is a code / pseudo-code hybrid of what I'm trying to do...
```
Container(
height: 200,
width: 300,
decoration: BoxDecoration(
image: DecorationImage(
image: (AssetImage('assets/images/${image_id}.jpg') exists) //pseudo-code here
? AssetImage('assets/images/${image_id}.jpg')
: AssetImage('assets/images/default.jpg'),
fit: BoxFit.cover,
),
),
);
``` | 2020/10/28 | [
"https://Stackoverflow.com/questions/64576412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11615071/"
]
| You should know if the asset exists as you're the responsible for adding those.
One option you have is by using: [**FlutterGen**](https://github.com/FlutterGen/flutter_gen) This library will create variables, method, etc for all your assets, if the variable is null, then, there you go.
You can also try to get the image like this:
```
final assetImage = Image.asset('path/to/asset.jpg');
```
and then check if that image is null or not. Even, if you want, you can take that and pre cache your image like this:
```
await precacheImage(assetImage.image, context);
``` | You can [list](https://stackoverflow.com/a/56555070/7314211) all of the assets. Then you can check if certain asset is exist or not. |
64,576,412 | To preface, I have reviewed the post [here](https://stackoverflow.com/questions/52908923/check-if-asset-exist-in-flutter), but am still having trouble.
I am building a container that is decorated with an image, only if that image exists in the assets/images/ folder. If it does not exist, the container is decorated with a default image instead.
The image path is formatted string using a variable, image\_id, that assumes a String response from an API.
Here is a code / pseudo-code hybrid of what I'm trying to do...
```
Container(
height: 200,
width: 300,
decoration: BoxDecoration(
image: DecorationImage(
image: (AssetImage('assets/images/${image_id}.jpg') exists) //pseudo-code here
? AssetImage('assets/images/${image_id}.jpg')
: AssetImage('assets/images/default.jpg'),
fit: BoxFit.cover,
),
),
);
``` | 2020/10/28 | [
"https://Stackoverflow.com/questions/64576412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11615071/"
]
| You should know if the asset exists as you're the responsible for adding those.
One option you have is by using: [**FlutterGen**](https://github.com/FlutterGen/flutter_gen) This library will create variables, method, etc for all your assets, if the variable is null, then, there you go.
You can also try to get the image like this:
```
final assetImage = Image.asset('path/to/asset.jpg');
```
and then check if that image is null or not. Even, if you want, you can take that and pre cache your image like this:
```
await precacheImage(assetImage.image, context);
``` | You are responsible for adding assets. Thus you will know if it's there or not. |
8,467,908 | I have some utility methods that use `Microsoft.Web.Administration.ServerManager` that I've been having some issues with. Use the following dead simple code for illustration purposes.
```
using(var mgr = new ServerManager())
{
foreach(var site in mgr.Sites)
{
Console.WriteLine(site.Name);
}
}
```
If I put that code directly in a console application and run it, it will get and list the IIS express websites. If I run that app from an elevated command prompt, it will list the IIS7 websites. A little inconvenient, but so far so good.
If instead I put that code in a class library that is referenced and called by the console app, it will ALWAYS list the IIS Express sites, even if the console app is elevated.
Google has led me to try the following, with no luck.
```
//This returns IIS express
var mgr = new ServerManager();
//This returns IIS express
var mgr = ServerManager.OpenRemote(Environment.MachineName);
//This throws an exception
var mgr = new ServerManager(@"%windir%\system32\inetsrv\config\applicationhost.config");
```
Evidently I've misunderstood something in the way an "elevated" process runs. Shouldn't everything executing in an elevated process, even code from another dll, be run with elevated rights? Evidently not?
Thanks for the help! | 2011/12/11 | [
"https://Stackoverflow.com/questions/8467908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55142/"
]
| Make sure you are adding the reference to the correct Microsoft.Web.Administration, should be v7.0.0.0 that is located under c:\windows\system32\inetsrv\
It looks like you are adding a reference to IIS Express's Microsoft.Web.Administraiton which will give you that behavior | Your question helped me find the answer for PowerShell, so if the Internet is searching for how to do that:
```
$assembly = [System.Reflection.Assembly]::LoadFrom("$env:systemroot\system32\inetsrv\Microsoft.Web.Administration.dll")
# load IIS express
$iis = new-object Microsoft.Web.Administration.ServerManager
$iis.Sites
# load IIS proper
$iis = new-object Microsoft.Web.Administration.ServerManager "$env:systemroot\system32\inetsrv\config\applicationhost.config"
$iis.Sites
``` |
8,467,908 | I have some utility methods that use `Microsoft.Web.Administration.ServerManager` that I've been having some issues with. Use the following dead simple code for illustration purposes.
```
using(var mgr = new ServerManager())
{
foreach(var site in mgr.Sites)
{
Console.WriteLine(site.Name);
}
}
```
If I put that code directly in a console application and run it, it will get and list the IIS express websites. If I run that app from an elevated command prompt, it will list the IIS7 websites. A little inconvenient, but so far so good.
If instead I put that code in a class library that is referenced and called by the console app, it will ALWAYS list the IIS Express sites, even if the console app is elevated.
Google has led me to try the following, with no luck.
```
//This returns IIS express
var mgr = new ServerManager();
//This returns IIS express
var mgr = ServerManager.OpenRemote(Environment.MachineName);
//This throws an exception
var mgr = new ServerManager(@"%windir%\system32\inetsrv\config\applicationhost.config");
```
Evidently I've misunderstood something in the way an "elevated" process runs. Shouldn't everything executing in an elevated process, even code from another dll, be run with elevated rights? Evidently not?
Thanks for the help! | 2011/12/11 | [
"https://Stackoverflow.com/questions/8467908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55142/"
]
| Make sure you are adding the reference to the correct Microsoft.Web.Administration, should be v7.0.0.0 that is located under c:\windows\system32\inetsrv\
It looks like you are adding a reference to IIS Express's Microsoft.Web.Administraiton which will give you that behavior | **CAUTION! Using this approach we have seen seemingly random issues such as "unsupported operation" exceptions, failure to add/remove HTTPS bindings, failure to start/stop application pools when running in IIS Express, and other problems. It is unknown whether this is due to IIS being generally buggy or due to the unorthodox approach described here. In general, my impression is that all tools for automating IIS (appcmd, Microsoft.Web.Administration, PowerShell, ...) are wonky and unstable, especially across different OS versions. Good testing is (as always) advisable!**
**EDIT: Please also see the comments on this answer as to why this approach may be unstable.**
The regular `Microsoft.Web.Administration` package installed from NuGet works fine. No need to copy any system DLLs.
The obvious solution from the official documentation also works fine:
```
ServerManager iisManager = new ServerManager(Environment.SystemDirectory + @"inetsrv\config\applicationHost.config");
```
This works even if you execute the above from within the application pool of IIS Express. You will still see the configuration of the "real" IIS. You will even be able to add new sites, as long as your application runs as a user with permission to do so.
Note, however that the constructor above is documented as "Microsoft internal use only":
<https://msdn.microsoft.com/en-us/library/ms617371(v=vs.90).aspx> |
8,467,908 | I have some utility methods that use `Microsoft.Web.Administration.ServerManager` that I've been having some issues with. Use the following dead simple code for illustration purposes.
```
using(var mgr = new ServerManager())
{
foreach(var site in mgr.Sites)
{
Console.WriteLine(site.Name);
}
}
```
If I put that code directly in a console application and run it, it will get and list the IIS express websites. If I run that app from an elevated command prompt, it will list the IIS7 websites. A little inconvenient, but so far so good.
If instead I put that code in a class library that is referenced and called by the console app, it will ALWAYS list the IIS Express sites, even if the console app is elevated.
Google has led me to try the following, with no luck.
```
//This returns IIS express
var mgr = new ServerManager();
//This returns IIS express
var mgr = ServerManager.OpenRemote(Environment.MachineName);
//This throws an exception
var mgr = new ServerManager(@"%windir%\system32\inetsrv\config\applicationhost.config");
```
Evidently I've misunderstood something in the way an "elevated" process runs. Shouldn't everything executing in an elevated process, even code from another dll, be run with elevated rights? Evidently not?
Thanks for the help! | 2011/12/11 | [
"https://Stackoverflow.com/questions/8467908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55142/"
]
| Make sure you are adding the reference to the correct Microsoft.Web.Administration, should be v7.0.0.0 that is located under c:\windows\system32\inetsrv\
It looks like you are adding a reference to IIS Express's Microsoft.Web.Administraiton which will give you that behavior | ```
var iisManager = new ServerManager(Environment.SystemDirectory + "\\inetsrv\\config\\applicationhost.config");
```
This works perfectly. No need to change any references |
8,467,908 | I have some utility methods that use `Microsoft.Web.Administration.ServerManager` that I've been having some issues with. Use the following dead simple code for illustration purposes.
```
using(var mgr = new ServerManager())
{
foreach(var site in mgr.Sites)
{
Console.WriteLine(site.Name);
}
}
```
If I put that code directly in a console application and run it, it will get and list the IIS express websites. If I run that app from an elevated command prompt, it will list the IIS7 websites. A little inconvenient, but so far so good.
If instead I put that code in a class library that is referenced and called by the console app, it will ALWAYS list the IIS Express sites, even if the console app is elevated.
Google has led me to try the following, with no luck.
```
//This returns IIS express
var mgr = new ServerManager();
//This returns IIS express
var mgr = ServerManager.OpenRemote(Environment.MachineName);
//This throws an exception
var mgr = new ServerManager(@"%windir%\system32\inetsrv\config\applicationhost.config");
```
Evidently I've misunderstood something in the way an "elevated" process runs. Shouldn't everything executing in an elevated process, even code from another dll, be run with elevated rights? Evidently not?
Thanks for the help! | 2011/12/11 | [
"https://Stackoverflow.com/questions/8467908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55142/"
]
| Your question helped me find the answer for PowerShell, so if the Internet is searching for how to do that:
```
$assembly = [System.Reflection.Assembly]::LoadFrom("$env:systemroot\system32\inetsrv\Microsoft.Web.Administration.dll")
# load IIS express
$iis = new-object Microsoft.Web.Administration.ServerManager
$iis.Sites
# load IIS proper
$iis = new-object Microsoft.Web.Administration.ServerManager "$env:systemroot\system32\inetsrv\config\applicationhost.config"
$iis.Sites
``` | **CAUTION! Using this approach we have seen seemingly random issues such as "unsupported operation" exceptions, failure to add/remove HTTPS bindings, failure to start/stop application pools when running in IIS Express, and other problems. It is unknown whether this is due to IIS being generally buggy or due to the unorthodox approach described here. In general, my impression is that all tools for automating IIS (appcmd, Microsoft.Web.Administration, PowerShell, ...) are wonky and unstable, especially across different OS versions. Good testing is (as always) advisable!**
**EDIT: Please also see the comments on this answer as to why this approach may be unstable.**
The regular `Microsoft.Web.Administration` package installed from NuGet works fine. No need to copy any system DLLs.
The obvious solution from the official documentation also works fine:
```
ServerManager iisManager = new ServerManager(Environment.SystemDirectory + @"inetsrv\config\applicationHost.config");
```
This works even if you execute the above from within the application pool of IIS Express. You will still see the configuration of the "real" IIS. You will even be able to add new sites, as long as your application runs as a user with permission to do so.
Note, however that the constructor above is documented as "Microsoft internal use only":
<https://msdn.microsoft.com/en-us/library/ms617371(v=vs.90).aspx> |
8,467,908 | I have some utility methods that use `Microsoft.Web.Administration.ServerManager` that I've been having some issues with. Use the following dead simple code for illustration purposes.
```
using(var mgr = new ServerManager())
{
foreach(var site in mgr.Sites)
{
Console.WriteLine(site.Name);
}
}
```
If I put that code directly in a console application and run it, it will get and list the IIS express websites. If I run that app from an elevated command prompt, it will list the IIS7 websites. A little inconvenient, but so far so good.
If instead I put that code in a class library that is referenced and called by the console app, it will ALWAYS list the IIS Express sites, even if the console app is elevated.
Google has led me to try the following, with no luck.
```
//This returns IIS express
var mgr = new ServerManager();
//This returns IIS express
var mgr = ServerManager.OpenRemote(Environment.MachineName);
//This throws an exception
var mgr = new ServerManager(@"%windir%\system32\inetsrv\config\applicationhost.config");
```
Evidently I've misunderstood something in the way an "elevated" process runs. Shouldn't everything executing in an elevated process, even code from another dll, be run with elevated rights? Evidently not?
Thanks for the help! | 2011/12/11 | [
"https://Stackoverflow.com/questions/8467908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55142/"
]
| Your question helped me find the answer for PowerShell, so if the Internet is searching for how to do that:
```
$assembly = [System.Reflection.Assembly]::LoadFrom("$env:systemroot\system32\inetsrv\Microsoft.Web.Administration.dll")
# load IIS express
$iis = new-object Microsoft.Web.Administration.ServerManager
$iis.Sites
# load IIS proper
$iis = new-object Microsoft.Web.Administration.ServerManager "$env:systemroot\system32\inetsrv\config\applicationhost.config"
$iis.Sites
``` | ```
var iisManager = new ServerManager(Environment.SystemDirectory + "\\inetsrv\\config\\applicationhost.config");
```
This works perfectly. No need to change any references |
8,467,908 | I have some utility methods that use `Microsoft.Web.Administration.ServerManager` that I've been having some issues with. Use the following dead simple code for illustration purposes.
```
using(var mgr = new ServerManager())
{
foreach(var site in mgr.Sites)
{
Console.WriteLine(site.Name);
}
}
```
If I put that code directly in a console application and run it, it will get and list the IIS express websites. If I run that app from an elevated command prompt, it will list the IIS7 websites. A little inconvenient, but so far so good.
If instead I put that code in a class library that is referenced and called by the console app, it will ALWAYS list the IIS Express sites, even if the console app is elevated.
Google has led me to try the following, with no luck.
```
//This returns IIS express
var mgr = new ServerManager();
//This returns IIS express
var mgr = ServerManager.OpenRemote(Environment.MachineName);
//This throws an exception
var mgr = new ServerManager(@"%windir%\system32\inetsrv\config\applicationhost.config");
```
Evidently I've misunderstood something in the way an "elevated" process runs. Shouldn't everything executing in an elevated process, even code from another dll, be run with elevated rights? Evidently not?
Thanks for the help! | 2011/12/11 | [
"https://Stackoverflow.com/questions/8467908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55142/"
]
| **CAUTION! Using this approach we have seen seemingly random issues such as "unsupported operation" exceptions, failure to add/remove HTTPS bindings, failure to start/stop application pools when running in IIS Express, and other problems. It is unknown whether this is due to IIS being generally buggy or due to the unorthodox approach described here. In general, my impression is that all tools for automating IIS (appcmd, Microsoft.Web.Administration, PowerShell, ...) are wonky and unstable, especially across different OS versions. Good testing is (as always) advisable!**
**EDIT: Please also see the comments on this answer as to why this approach may be unstable.**
The regular `Microsoft.Web.Administration` package installed from NuGet works fine. No need to copy any system DLLs.
The obvious solution from the official documentation also works fine:
```
ServerManager iisManager = new ServerManager(Environment.SystemDirectory + @"inetsrv\config\applicationHost.config");
```
This works even if you execute the above from within the application pool of IIS Express. You will still see the configuration of the "real" IIS. You will even be able to add new sites, as long as your application runs as a user with permission to do so.
Note, however that the constructor above is documented as "Microsoft internal use only":
<https://msdn.microsoft.com/en-us/library/ms617371(v=vs.90).aspx> | ```
var iisManager = new ServerManager(Environment.SystemDirectory + "\\inetsrv\\config\\applicationhost.config");
```
This works perfectly. No need to change any references |
27,212,037 | What is the difference between the 2 lines below? They do the same thing so is there any difference ?
```
string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string filename = FileUpload1.PostedFile.FileName;
``` | 2014/11/30 | [
"https://Stackoverflow.com/questions/27212037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3994909/"
]
| In BASH you can use this utility function:
```
decodeURL() {
printf "$(sed 's#^file://##;s/+/ /g;s/%\(..\)/\\x\1/g;' <<< "$@")\n";
}
```
**Then call this function as:**
```
decodeURL 'file:///home/sashoalm/Has%20Spaces.txt'
/home/sashoalm/Has Spaces.txt
``` | [Urlencode](http://linux.die.net/man/1/urlencode) should do it (-d option)
>
> -d Do URL-decoding rather than encoding, according to RFC 1738. %HH and %hh strings are converted and other characters are passed through
> unmodified, with the exception that + is converted to space.
>
>
> |
27,212,037 | What is the difference between the 2 lines below? They do the same thing so is there any difference ?
```
string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string filename = FileUpload1.PostedFile.FileName;
``` | 2014/11/30 | [
"https://Stackoverflow.com/questions/27212037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3994909/"
]
| [Urlencode](http://linux.die.net/man/1/urlencode) should do it (-d option)
>
> -d Do URL-decoding rather than encoding, according to RFC 1738. %HH and %hh strings are converted and other characters are passed through
> unmodified, with the exception that + is converted to space.
>
>
> | GNU awk
```perl
#!/usr/bin/awk -fn
@include "ord"
BEGIN {
RS = "%.."
}
{
printf RT ? $0 chr("0x" substr(RT, 2)) : $0
}
```
Or
```
#!/bin/sh
awk -niord '{printf RT?$0chr("0x"substr(RT,2)):$0}' RS=%..
```
[How to decode URL-encoded string in shell?](https://stackoverflow.com/q/6250698/#14000368) |
27,212,037 | What is the difference between the 2 lines below? They do the same thing so is there any difference ?
```
string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string filename = FileUpload1.PostedFile.FileName;
``` | 2014/11/30 | [
"https://Stackoverflow.com/questions/27212037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3994909/"
]
| In BASH you can use this utility function:
```
decodeURL() {
printf "$(sed 's#^file://##;s/+/ /g;s/%\(..\)/\\x\1/g;' <<< "$@")\n";
}
```
**Then call this function as:**
```
decodeURL 'file:///home/sashoalm/Has%20Spaces.txt'
/home/sashoalm/Has Spaces.txt
``` | Perl to the rescue:
```
echo file:///home/sashoalm/Has%20Spaces.txt |\
perl -MURI -MURI::Escape -lne \
'print uri_unescape(URI->new($_)->path)'
```
See [URI](http://p3rl.org/URI) and [URI::Escape](http://p3rl.org/URI::Escape). |
27,212,037 | What is the difference between the 2 lines below? They do the same thing so is there any difference ?
```
string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string filename = FileUpload1.PostedFile.FileName;
``` | 2014/11/30 | [
"https://Stackoverflow.com/questions/27212037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3994909/"
]
| In BASH you can use this utility function:
```
decodeURL() {
printf "$(sed 's#^file://##;s/+/ /g;s/%\(..\)/\\x\1/g;' <<< "$@")\n";
}
```
**Then call this function as:**
```
decodeURL 'file:///home/sashoalm/Has%20Spaces.txt'
/home/sashoalm/Has Spaces.txt
``` | GNU awk
```perl
#!/usr/bin/awk -fn
@include "ord"
BEGIN {
RS = "%.."
}
{
printf RT ? $0 chr("0x" substr(RT, 2)) : $0
}
```
Or
```
#!/bin/sh
awk -niord '{printf RT?$0chr("0x"substr(RT,2)):$0}' RS=%..
```
[How to decode URL-encoded string in shell?](https://stackoverflow.com/q/6250698/#14000368) |
27,212,037 | What is the difference between the 2 lines below? They do the same thing so is there any difference ?
```
string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string filename = FileUpload1.PostedFile.FileName;
``` | 2014/11/30 | [
"https://Stackoverflow.com/questions/27212037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3994909/"
]
| Perl to the rescue:
```
echo file:///home/sashoalm/Has%20Spaces.txt |\
perl -MURI -MURI::Escape -lne \
'print uri_unescape(URI->new($_)->path)'
```
See [URI](http://p3rl.org/URI) and [URI::Escape](http://p3rl.org/URI::Escape). | GNU awk
```perl
#!/usr/bin/awk -fn
@include "ord"
BEGIN {
RS = "%.."
}
{
printf RT ? $0 chr("0x" substr(RT, 2)) : $0
}
```
Or
```
#!/bin/sh
awk -niord '{printf RT?$0chr("0x"substr(RT,2)):$0}' RS=%..
```
[How to decode URL-encoded string in shell?](https://stackoverflow.com/q/6250698/#14000368) |
10,741,179 | i have some jquery thats expanding/collapsing on click. i would like the first item to be expanded by default but im having trouble with the jquery. i've tried a few different angles to no avail. any help would be much appreciated!
<http://jsfiddle.net/trrJp/1/> | 2012/05/24 | [
"https://Stackoverflow.com/questions/10741179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1211700/"
]
| The original poster didn't select an answer I'm going to combine the previous two into one ***super*** answr! :P
You can enable word wrapping on all columns on the Spark DataGrid with variableRowHeight:
```
<s:DataGrid variableRowHeight="true">
</s:DataGrid>
```
Or you can enable word wrapping on an individual column by using the word wrap property on the default GridColumn item renderer:
```
<s:GridColumn dataField="fields.description" headerText="Description" >
<s:itemRenderer>
<fx:Component>
<s:DefaultGridItemRenderer wordWrap="true"/>
</fx:Component>
</s:itemRenderer>
</s:GridColumn>
```
Furthermore, in the Grid Column example I'd recommend setting a width if you want to prevent horizontal scroll bars:
```
<s:GridColumn width="{dataGrid.width-column1.width-column3.width}" dataField="fields.description" headerText="Description" >
<s:itemRenderer>
<fx:Component>
<s:DefaultGridItemRenderer wordWrap="true"/>
</fx:Component>
</s:itemRenderer>
</s:GridColumn>
```
I'm finding I have to set both variable row height to true and set the column width to get the behavior I'm looking for. | **[Edit]**
Oops, my original answer was referring to the MX `DataGridColumn` component, not the Spark `GridColumn`. Revised answer...
The default item renderer for the grid is `DataGridItemRenderer` and it has a word wrap property that you need to set to true. Not sure, but you might also have to set the `variableRowHeight` property of the grid to true as well...
To do this in MXML, it would look something like this:
```
<s:DataGrid variableRowHeight="true">
<s:itemRenderer>
<fx:Component>
<s:DataGridItemRenderer wordWrap="true" />
</fx:Component>
</s:itemRenderer>
</s:DataGrid>
``` |
10,741,179 | i have some jquery thats expanding/collapsing on click. i would like the first item to be expanded by default but im having trouble with the jquery. i've tried a few different angles to no avail. any help would be much appreciated!
<http://jsfiddle.net/trrJp/1/> | 2012/05/24 | [
"https://Stackoverflow.com/questions/10741179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1211700/"
]
| The original poster didn't select an answer I'm going to combine the previous two into one ***super*** answr! :P
You can enable word wrapping on all columns on the Spark DataGrid with variableRowHeight:
```
<s:DataGrid variableRowHeight="true">
</s:DataGrid>
```
Or you can enable word wrapping on an individual column by using the word wrap property on the default GridColumn item renderer:
```
<s:GridColumn dataField="fields.description" headerText="Description" >
<s:itemRenderer>
<fx:Component>
<s:DefaultGridItemRenderer wordWrap="true"/>
</fx:Component>
</s:itemRenderer>
</s:GridColumn>
```
Furthermore, in the Grid Column example I'd recommend setting a width if you want to prevent horizontal scroll bars:
```
<s:GridColumn width="{dataGrid.width-column1.width-column3.width}" dataField="fields.description" headerText="Description" >
<s:itemRenderer>
<fx:Component>
<s:DefaultGridItemRenderer wordWrap="true"/>
</fx:Component>
</s:itemRenderer>
</s:GridColumn>
```
I'm finding I have to set both variable row height to true and set the column width to get the behavior I'm looking for. | Until *flex4.6*, there is no **s**:DataGridItemRenderer, but there is **mx**:DataGridItemRenderer. So, the code would be:
```
<s:GridColumn headerText="foo" labelFunction="fooLabelFunction">
<s:itemRenderer>
<fx:Component>
<mx:DataGridItemRenderer wordWrap="true" />
</fx:Component>
</s:itemRenderer>
</s:GridColumn>
``` |
21,642,329 | Let`s say I have the following table
```
+----+-------+
| Id | Value |
+----+-------+
| 1 | 2.0 |
| 2 | 8.0 |
| 3 | 3.0 |
| 4 | 9.0 |
| 5 | 1.0 |
| 6 | 4.0 |
| 7 | 2.5 |
| 8 | 6.5 |
+----+-------+
```
I want to plot these values, but since my real table has thousands of values, I thought about getting and average for each X rows. Is there any way for me to do so for, ie, each 2 or 4 rows, like below:
```
2
+-----+------+
| 1-2 | 5.0 |
| 3-4 | 6.0 |
| 5-6 | 2.5 |
| 7-8 | 4.5 |
+-----+------+
4
+-----+------+
| 1-4 | 5.5 |
| 5-8 | 3.5 |
+-----+------+
```
Also, is there any way to make this X value dynamic, based on the total number of rows in my table? Something like, if I have 1000 rows, the average will be calculated based on each 200 rows (1000/5), but if I have 20, calculate it based on each 4 rows (20/5).
I know how to do that programmatically, but is there any way to do so using pure SQL?
EDIT: I need it to work on mysql. | 2014/02/08 | [
"https://Stackoverflow.com/questions/21642329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2278986/"
]
| Depending on your DBMS, something like this will work:
```
SELECT
ChunkStart = Min(Id),
ChunkEnd = Max(Id),
Value = Avg(Value)
FROM
(
SELECT
Chunk = NTILE(5) OVER (ORDER BY Id),
*
FROM
YourTable
) AS T
GROUP BY
Chunk
ORDER BY
ChunkStart;
```
This creates 5 groups or chunks no matter how many rows there are, as you requested.
If you have no windowing functions you can fake it:
```
SELECT
ChunkStart = Min(Id),
ChunkEnd = Max(Id),
Value = Avg(Value)
FROM
YourTable
GROUP BY
(Id - 1) / (((SELECT Count(*) FROM YourTable) + 4) / 5)
;
```
I made some assumptions here such as `Id` beginning with 1 and there being no gaps, and that you would want the last group too small instead of too big if things didn't divide evenly. I also assumed integer division would result as in Ms SQL Server. | You can use modulos operator to act on every Nth row of the table. This example would get the average value for every 10th row:
```
select avg(Value) from some_table where id % 10 = 0;
```
You could then do a count of the rows in the table, apply some factor to that, and use that value as a dynamic interval:
```
select avg(Value) from some_table where id % (select round(count(*)/1000) from some_table) = 0;
```
You'll need to figure out the best interval based on the actual number of rows you have in the table of course.
EDIT:
Rereading you post I realize this is getting an average of every Nth row, and not each sequential N rows. I'm not sure if this would suffice, or if you specifically need sequential averages. |
21,642,329 | Let`s say I have the following table
```
+----+-------+
| Id | Value |
+----+-------+
| 1 | 2.0 |
| 2 | 8.0 |
| 3 | 3.0 |
| 4 | 9.0 |
| 5 | 1.0 |
| 6 | 4.0 |
| 7 | 2.5 |
| 8 | 6.5 |
+----+-------+
```
I want to plot these values, but since my real table has thousands of values, I thought about getting and average for each X rows. Is there any way for me to do so for, ie, each 2 or 4 rows, like below:
```
2
+-----+------+
| 1-2 | 5.0 |
| 3-4 | 6.0 |
| 5-6 | 2.5 |
| 7-8 | 4.5 |
+-----+------+
4
+-----+------+
| 1-4 | 5.5 |
| 5-8 | 3.5 |
+-----+------+
```
Also, is there any way to make this X value dynamic, based on the total number of rows in my table? Something like, if I have 1000 rows, the average will be calculated based on each 200 rows (1000/5), but if I have 20, calculate it based on each 4 rows (20/5).
I know how to do that programmatically, but is there any way to do so using pure SQL?
EDIT: I need it to work on mysql. | 2014/02/08 | [
"https://Stackoverflow.com/questions/21642329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2278986/"
]
| You can use modulos operator to act on every Nth row of the table. This example would get the average value for every 10th row:
```
select avg(Value) from some_table where id % 10 = 0;
```
You could then do a count of the rows in the table, apply some factor to that, and use that value as a dynamic interval:
```
select avg(Value) from some_table where id % (select round(count(*)/1000) from some_table) = 0;
```
You'll need to figure out the best interval based on the actual number of rows you have in the table of course.
EDIT:
Rereading you post I realize this is getting an average of every Nth row, and not each sequential N rows. I'm not sure if this would suffice, or if you specifically need sequential averages. | Look at the NTILE function (as in quartile, quintile, decile, percentile). You can use it to split your data evenly into a number of buckets - in your case it seems you would like five.
Then you can use AVG to calculate an average for each bucket.
NTILE is in SQL-99 so most DBMSes should have it. |
21,642,329 | Let`s say I have the following table
```
+----+-------+
| Id | Value |
+----+-------+
| 1 | 2.0 |
| 2 | 8.0 |
| 3 | 3.0 |
| 4 | 9.0 |
| 5 | 1.0 |
| 6 | 4.0 |
| 7 | 2.5 |
| 8 | 6.5 |
+----+-------+
```
I want to plot these values, but since my real table has thousands of values, I thought about getting and average for each X rows. Is there any way for me to do so for, ie, each 2 or 4 rows, like below:
```
2
+-----+------+
| 1-2 | 5.0 |
| 3-4 | 6.0 |
| 5-6 | 2.5 |
| 7-8 | 4.5 |
+-----+------+
4
+-----+------+
| 1-4 | 5.5 |
| 5-8 | 3.5 |
+-----+------+
```
Also, is there any way to make this X value dynamic, based on the total number of rows in my table? Something like, if I have 1000 rows, the average will be calculated based on each 200 rows (1000/5), but if I have 20, calculate it based on each 4 rows (20/5).
I know how to do that programmatically, but is there any way to do so using pure SQL?
EDIT: I need it to work on mysql. | 2014/02/08 | [
"https://Stackoverflow.com/questions/21642329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2278986/"
]
| You can use modulos operator to act on every Nth row of the table. This example would get the average value for every 10th row:
```
select avg(Value) from some_table where id % 10 = 0;
```
You could then do a count of the rows in the table, apply some factor to that, and use that value as a dynamic interval:
```
select avg(Value) from some_table where id % (select round(count(*)/1000) from some_table) = 0;
```
You'll need to figure out the best interval based on the actual number of rows you have in the table of course.
EDIT:
Rereading you post I realize this is getting an average of every Nth row, and not each sequential N rows. I'm not sure if this would suffice, or if you specifically need sequential averages. | You can try that
```
CREATE TABLE #YourTable
(
ID int
,[Value] float
)
INSERT #YourTable (ID, [Value]) VALUES
(1,2.0)
,(2,8.0)
,(3,3.0)
,(4,9.0)
,(5,1.0)
,(6,4.0)
,(7,2.5)
,(8,6.5)
SELECT
ID = MIN(ID) + '-' + MAX(ID)
,[Value] = AVG([Value])
FROM
(
SELECT
GRP = ((ROW_NUMBER() OVER(ORDER BY ID) -1) / 2) + 1
,ID = CONVERT(VARCHAR(10), ID)
,[Value]
FROM
#YourTable
) GrpTable
GROUP BY
GRP
DROP TABLE #YourTable
``` |
21,642,329 | Let`s say I have the following table
```
+----+-------+
| Id | Value |
+----+-------+
| 1 | 2.0 |
| 2 | 8.0 |
| 3 | 3.0 |
| 4 | 9.0 |
| 5 | 1.0 |
| 6 | 4.0 |
| 7 | 2.5 |
| 8 | 6.5 |
+----+-------+
```
I want to plot these values, but since my real table has thousands of values, I thought about getting and average for each X rows. Is there any way for me to do so for, ie, each 2 or 4 rows, like below:
```
2
+-----+------+
| 1-2 | 5.0 |
| 3-4 | 6.0 |
| 5-6 | 2.5 |
| 7-8 | 4.5 |
+-----+------+
4
+-----+------+
| 1-4 | 5.5 |
| 5-8 | 3.5 |
+-----+------+
```
Also, is there any way to make this X value dynamic, based on the total number of rows in my table? Something like, if I have 1000 rows, the average will be calculated based on each 200 rows (1000/5), but if I have 20, calculate it based on each 4 rows (20/5).
I know how to do that programmatically, but is there any way to do so using pure SQL?
EDIT: I need it to work on mysql. | 2014/02/08 | [
"https://Stackoverflow.com/questions/21642329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2278986/"
]
| Depending on your DBMS, something like this will work:
```
SELECT
ChunkStart = Min(Id),
ChunkEnd = Max(Id),
Value = Avg(Value)
FROM
(
SELECT
Chunk = NTILE(5) OVER (ORDER BY Id),
*
FROM
YourTable
) AS T
GROUP BY
Chunk
ORDER BY
ChunkStart;
```
This creates 5 groups or chunks no matter how many rows there are, as you requested.
If you have no windowing functions you can fake it:
```
SELECT
ChunkStart = Min(Id),
ChunkEnd = Max(Id),
Value = Avg(Value)
FROM
YourTable
GROUP BY
(Id - 1) / (((SELECT Count(*) FROM YourTable) + 4) / 5)
;
```
I made some assumptions here such as `Id` beginning with 1 and there being no gaps, and that you would want the last group too small instead of too big if things didn't divide evenly. I also assumed integer division would result as in Ms SQL Server. | Look at the NTILE function (as in quartile, quintile, decile, percentile). You can use it to split your data evenly into a number of buckets - in your case it seems you would like five.
Then you can use AVG to calculate an average for each bucket.
NTILE is in SQL-99 so most DBMSes should have it. |
21,642,329 | Let`s say I have the following table
```
+----+-------+
| Id | Value |
+----+-------+
| 1 | 2.0 |
| 2 | 8.0 |
| 3 | 3.0 |
| 4 | 9.0 |
| 5 | 1.0 |
| 6 | 4.0 |
| 7 | 2.5 |
| 8 | 6.5 |
+----+-------+
```
I want to plot these values, but since my real table has thousands of values, I thought about getting and average for each X rows. Is there any way for me to do so for, ie, each 2 or 4 rows, like below:
```
2
+-----+------+
| 1-2 | 5.0 |
| 3-4 | 6.0 |
| 5-6 | 2.5 |
| 7-8 | 4.5 |
+-----+------+
4
+-----+------+
| 1-4 | 5.5 |
| 5-8 | 3.5 |
+-----+------+
```
Also, is there any way to make this X value dynamic, based on the total number of rows in my table? Something like, if I have 1000 rows, the average will be calculated based on each 200 rows (1000/5), but if I have 20, calculate it based on each 4 rows (20/5).
I know how to do that programmatically, but is there any way to do so using pure SQL?
EDIT: I need it to work on mysql. | 2014/02/08 | [
"https://Stackoverflow.com/questions/21642329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2278986/"
]
| Depending on your DBMS, something like this will work:
```
SELECT
ChunkStart = Min(Id),
ChunkEnd = Max(Id),
Value = Avg(Value)
FROM
(
SELECT
Chunk = NTILE(5) OVER (ORDER BY Id),
*
FROM
YourTable
) AS T
GROUP BY
Chunk
ORDER BY
ChunkStart;
```
This creates 5 groups or chunks no matter how many rows there are, as you requested.
If you have no windowing functions you can fake it:
```
SELECT
ChunkStart = Min(Id),
ChunkEnd = Max(Id),
Value = Avg(Value)
FROM
YourTable
GROUP BY
(Id - 1) / (((SELECT Count(*) FROM YourTable) + 4) / 5)
;
```
I made some assumptions here such as `Id` beginning with 1 and there being no gaps, and that you would want the last group too small instead of too big if things didn't divide evenly. I also assumed integer division would result as in Ms SQL Server. | You can try that
```
CREATE TABLE #YourTable
(
ID int
,[Value] float
)
INSERT #YourTable (ID, [Value]) VALUES
(1,2.0)
,(2,8.0)
,(3,3.0)
,(4,9.0)
,(5,1.0)
,(6,4.0)
,(7,2.5)
,(8,6.5)
SELECT
ID = MIN(ID) + '-' + MAX(ID)
,[Value] = AVG([Value])
FROM
(
SELECT
GRP = ((ROW_NUMBER() OVER(ORDER BY ID) -1) / 2) + 1
,ID = CONVERT(VARCHAR(10), ID)
,[Value]
FROM
#YourTable
) GrpTable
GROUP BY
GRP
DROP TABLE #YourTable
``` |
21,642,329 | Let`s say I have the following table
```
+----+-------+
| Id | Value |
+----+-------+
| 1 | 2.0 |
| 2 | 8.0 |
| 3 | 3.0 |
| 4 | 9.0 |
| 5 | 1.0 |
| 6 | 4.0 |
| 7 | 2.5 |
| 8 | 6.5 |
+----+-------+
```
I want to plot these values, but since my real table has thousands of values, I thought about getting and average for each X rows. Is there any way for me to do so for, ie, each 2 or 4 rows, like below:
```
2
+-----+------+
| 1-2 | 5.0 |
| 3-4 | 6.0 |
| 5-6 | 2.5 |
| 7-8 | 4.5 |
+-----+------+
4
+-----+------+
| 1-4 | 5.5 |
| 5-8 | 3.5 |
+-----+------+
```
Also, is there any way to make this X value dynamic, based on the total number of rows in my table? Something like, if I have 1000 rows, the average will be calculated based on each 200 rows (1000/5), but if I have 20, calculate it based on each 4 rows (20/5).
I know how to do that programmatically, but is there any way to do so using pure SQL?
EDIT: I need it to work on mysql. | 2014/02/08 | [
"https://Stackoverflow.com/questions/21642329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2278986/"
]
| Look at the NTILE function (as in quartile, quintile, decile, percentile). You can use it to split your data evenly into a number of buckets - in your case it seems you would like five.
Then you can use AVG to calculate an average for each bucket.
NTILE is in SQL-99 so most DBMSes should have it. | You can try that
```
CREATE TABLE #YourTable
(
ID int
,[Value] float
)
INSERT #YourTable (ID, [Value]) VALUES
(1,2.0)
,(2,8.0)
,(3,3.0)
,(4,9.0)
,(5,1.0)
,(6,4.0)
,(7,2.5)
,(8,6.5)
SELECT
ID = MIN(ID) + '-' + MAX(ID)
,[Value] = AVG([Value])
FROM
(
SELECT
GRP = ((ROW_NUMBER() OVER(ORDER BY ID) -1) / 2) + 1
,ID = CONVERT(VARCHAR(10), ID)
,[Value]
FROM
#YourTable
) GrpTable
GROUP BY
GRP
DROP TABLE #YourTable
``` |
1,584,983 | 1. I have an open folder in VSCode, eg `/folders/project1`, this is my workspace.
2. I want to add a file from outside of this folder, eg `/media/files/file1`.
I wish there was a VSCode command that displays a file picker that I can select any file on my computer's memory, and that file ends up in a folder opened as workspace.
For example:
3. In VSCode select the file `/media/files/file1` and it lands in workspace as `/folders/project1/file1`
How to do it? I can't find anything.
Of course I know I can do this manually in the file manager, but I want to do it without leaving VSCode. | 2020/09/12 | [
"https://superuser.com/questions/1584983",
"https://superuser.com",
"https://superuser.com/users/1050966/"
]
| You can use [PowerToys](https://github.com/microsoft/PowerToys) from Microsoft. One of the toys Keyboard Manager is made just for what you are looking for:
>
> Keyboard Manager allows you to customize the keyboard to be more productive by remapping keys and creating your own keyboard shortcuts. This PowerToy requires Windows 10 1903 (build 18362) or later.
>
>
>
To use it, go to the PowerToys settings, select Keyboard Manager, then click Remap Key.
[](https://i.stack.imgur.com/o2Pgb.png)
Select the key that should be remapped plus the key that should take its place. Click `OK`. That's it.
[](https://i.stack.imgur.com/0r97Y.png) | Sure, you can use a scripting language named AutoHotKey for creating custom hotkeys and remapping one keys to another. You can find tutorial and documentation in their [official website](https://www.autohotkey.com/docs/Tutorial.htm). |
37,099,617 | I'm having difficulties with some recoding (filling in empty cells in R or SPSS)
I'm working with a long format data-set (in order to run a multilevel model) where each respondent (ID-variable) has three rows, so three times the same ID number below each other (for three different momemts in time).
The problem is that for a second variable (ancestry of respondent) only the first row has a value but the two second rows for each respondent misses that (same) value (0/1). Can any one help? I'm only used to recoding within the same row... below a the data format.
```
ID Ancestry
1003 1
1003 .
1003 .
1004 0
1004 .
1004 .
1005 1
1005 .
1005 .
``` | 2016/05/08 | [
"https://Stackoverflow.com/questions/37099617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5235404/"
]
| We can use `na.locf` assuming that `.` implies `NA` values.
```
library(zoo)
df1$Ancestry <- na.locf(df1$Ancestry)
```
If the column is non-numeric i.e. have `.` as values, then we need to convert it to numeric so that the `.` coerce to NA and then we apply `na.locf` on it
```
df1$Ancestry <- na.locf(as.numeric(df1$Ancestry))
df1$Ancestry
#[1] 1 1 1 0 0 0 1 1 1
```
If it needs to be grouped by "ID"
```
library(data.table)
setDT(df1)[, Ancestry := na.locf(Ancestry), by = ID]
``` | In SPSS this should do the job, assuming the "Ancestry" variable is numeric:
```
AGGREGATE /OUTFILE=* MODE=ADDVARIABLES OVERWRITEVARS=YES/BREAK=ID /Ancestry=MAX(Ancestry).
```
If "Ancestry" is a string, you could go this way:
```
sort cases by ID Ancestry (d).
if ID=lag(ID) and Ancestry="" Ancestry=lag(Ancestry).
execute.
``` |
37,099,617 | I'm having difficulties with some recoding (filling in empty cells in R or SPSS)
I'm working with a long format data-set (in order to run a multilevel model) where each respondent (ID-variable) has three rows, so three times the same ID number below each other (for three different momemts in time).
The problem is that for a second variable (ancestry of respondent) only the first row has a value but the two second rows for each respondent misses that (same) value (0/1). Can any one help? I'm only used to recoding within the same row... below a the data format.
```
ID Ancestry
1003 1
1003 .
1003 .
1004 0
1004 .
1004 .
1005 1
1005 .
1005 .
``` | 2016/05/08 | [
"https://Stackoverflow.com/questions/37099617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5235404/"
]
| We can use `na.locf` assuming that `.` implies `NA` values.
```
library(zoo)
df1$Ancestry <- na.locf(df1$Ancestry)
```
If the column is non-numeric i.e. have `.` as values, then we need to convert it to numeric so that the `.` coerce to NA and then we apply `na.locf` on it
```
df1$Ancestry <- na.locf(as.numeric(df1$Ancestry))
df1$Ancestry
#[1] 1 1 1 0 0 0 1 1 1
```
If it needs to be grouped by "ID"
```
library(data.table)
setDT(df1)[, Ancestry := na.locf(Ancestry), by = ID]
``` | Another easy way of achieving this is in `R` the following, using the fact that the actual value always occurs in the first position for each ID:
```
library(dplyr)
df %>% group_by(ID) %>% mutate(Ancestry = Ancestry[1])
Source: local data frame [9 x 2]
Groups: ID [3]
ID Ancestry
(int) (chr)
1 1003 1
2 1003 1
3 1003 1
4 1004 0
5 1004 0
6 1004 0
7 1005 1
8 1005 1
9 1005 1
```
If you prefer a `base` solution, I think what I would probably have done is the following, though there are many ways of achieving the same: First, note that if `df` is your dataframe, then
```
df$Ancestry <- as.numeric(df$Ancestry)
```
will coerce the `.` into `NA`. Then we could use
```
df_id <- df[complete.cases(df),]
df$Ancestry <- NULL
df <- merge(df, df_id, all.x = T)
```
which gives the same output. Here, I take a `dataframe` that consists only of complete entries, and `merge` it back onto the original `dataframe`. |
37,099,617 | I'm having difficulties with some recoding (filling in empty cells in R or SPSS)
I'm working with a long format data-set (in order to run a multilevel model) where each respondent (ID-variable) has three rows, so three times the same ID number below each other (for three different momemts in time).
The problem is that for a second variable (ancestry of respondent) only the first row has a value but the two second rows for each respondent misses that (same) value (0/1). Can any one help? I'm only used to recoding within the same row... below a the data format.
```
ID Ancestry
1003 1
1003 .
1003 .
1004 0
1004 .
1004 .
1005 1
1005 .
1005 .
``` | 2016/05/08 | [
"https://Stackoverflow.com/questions/37099617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5235404/"
]
| We can use `na.locf` assuming that `.` implies `NA` values.
```
library(zoo)
df1$Ancestry <- na.locf(df1$Ancestry)
```
If the column is non-numeric i.e. have `.` as values, then we need to convert it to numeric so that the `.` coerce to NA and then we apply `na.locf` on it
```
df1$Ancestry <- na.locf(as.numeric(df1$Ancestry))
df1$Ancestry
#[1] 1 1 1 0 0 0 1 1 1
```
If it needs to be grouped by "ID"
```
library(data.table)
setDT(df1)[, Ancestry := na.locf(Ancestry), by = ID]
``` | Once you convert the `.`s to `NA` by your favorite method, this is exactly what `tidyr::fill` was designed to do:
```
library(tidyr)
df %>% extract(Ancestry, 'Ancestry', convert = TRUE) %>% fill(Ancestry)
#
# ID Ancestry
# 1 1003 1
# 2 1003 1
# 3 1003 1
# 4 1004 0
# 5 1004 0
# 6 1004 0
# 7 1005 1
# 8 1005 1
# 9 1005 1
``` |
37,099,617 | I'm having difficulties with some recoding (filling in empty cells in R or SPSS)
I'm working with a long format data-set (in order to run a multilevel model) where each respondent (ID-variable) has three rows, so three times the same ID number below each other (for three different momemts in time).
The problem is that for a second variable (ancestry of respondent) only the first row has a value but the two second rows for each respondent misses that (same) value (0/1). Can any one help? I'm only used to recoding within the same row... below a the data format.
```
ID Ancestry
1003 1
1003 .
1003 .
1004 0
1004 .
1004 .
1005 1
1005 .
1005 .
``` | 2016/05/08 | [
"https://Stackoverflow.com/questions/37099617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5235404/"
]
| We can use `na.locf` assuming that `.` implies `NA` values.
```
library(zoo)
df1$Ancestry <- na.locf(df1$Ancestry)
```
If the column is non-numeric i.e. have `.` as values, then we need to convert it to numeric so that the `.` coerce to NA and then we apply `na.locf` on it
```
df1$Ancestry <- na.locf(as.numeric(df1$Ancestry))
df1$Ancestry
#[1] 1 1 1 0 0 0 1 1 1
```
If it needs to be grouped by "ID"
```
library(data.table)
setDT(df1)[, Ancestry := na.locf(Ancestry), by = ID]
``` | ```
IF (ID EQ LAG(ID)) Ancestry=LAG(Ancestry).
```
Or alternatively:
```
IF (ID EQ LAG(ID) AND MISSING(Ancestry)) Ancestry=LAG(Ancestry).
``` |
80,649 | I am working on a physics reserach project for school and I have run into some troubles working Mathematica. I am a fairly inexperienced mathematica user so any help would very much be appreciated.
I need to find the roots of the transcendental equation
$$\zeta\_n \tan(\zeta) - \sqrt{R^2-\zeta^2\_n}=0$$
and then collect them into a list, $\{\zeta\_n\}$, which I can sum over.
FindRoot works but only finds one root at a time. For example $R^2=18$ gives
>
> FindRoot[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, {zeta, 3}]
>
>
> {zeta -> 3.66808}
> From a plot of the function I know there should be two roots for this particular value of $R$, however FindRoot only gives one.
>
>
>
I have had no luck with NSolve or Solve either.
>
> NSolve[xi[zeta, Erg4]- zeta\*Tan[zeta] == 0, zeta]
>
>
> NSolve[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, zeta]
>
>
>
Also once I have succeeded in finding all roots how does one put them in an indexed set ${\zeta\_n}$. | 2015/04/22 | [
"https://mathematica.stackexchange.com/questions/80649",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/27986/"
]
| ```
With[{maxR = 10},
Manipulate[
expr = Sqrt[R^2 - zeta^2] - zeta Tan[zeta];
zero = zeta /. NSolve[{expr == 0,
R^2 - zeta^2 >= 0}, zeta] // Quiet;
Column[{
Plot[expr, {zeta, -maxR, maxR},
Exclusions -> {Cos[zeta] == 0},
PlotRange -> {{-maxR, maxR}, {-25, 40}},
Epilog -> {Red, AbsolutePointSize[4],
Point[{#, 0} & /@ zero]},
AspectRatio -> 1],
zero},
Alignment -> Center],
{{R, Sqrt[18]}, 0, maxR, Appearance -> "Labeled"}]]
```
 | If the goal is only to obtain the sum of positive roots, then
```
f[r_] := Total[ΞΆ /. NSolve[{Sqrt[r^2 - ΞΆ^2] - ΞΆ Tan[ΞΆ] == 0,
r^2 - ΞΆ^2 >= 0, ΞΆ > 0}, ΞΆ]]
```
produces this quantity. For instance,
```
Plot[f[r], {r, .1, 10}, AxesLabel -> {R, Total}]
```

`Quiet` is used only to suppress the occasional information message,
```
Solve::ratnz: Solve was unable to solve the system with inexact coefficients. The answer was obtained by solving a corresponding exact system and numericizing the result. >>
``` |
80,649 | I am working on a physics reserach project for school and I have run into some troubles working Mathematica. I am a fairly inexperienced mathematica user so any help would very much be appreciated.
I need to find the roots of the transcendental equation
$$\zeta\_n \tan(\zeta) - \sqrt{R^2-\zeta^2\_n}=0$$
and then collect them into a list, $\{\zeta\_n\}$, which I can sum over.
FindRoot works but only finds one root at a time. For example $R^2=18$ gives
>
> FindRoot[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, {zeta, 3}]
>
>
> {zeta -> 3.66808}
> From a plot of the function I know there should be two roots for this particular value of $R$, however FindRoot only gives one.
>
>
>
I have had no luck with NSolve or Solve either.
>
> NSolve[xi[zeta, Erg4]- zeta\*Tan[zeta] == 0, zeta]
>
>
> NSolve[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, zeta]
>
>
>
Also once I have succeeded in finding all roots how does one put them in an indexed set ${\zeta\_n}$. | 2015/04/22 | [
"https://mathematica.stackexchange.com/questions/80649",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/27986/"
]
| ```
With[{maxR = 10},
Manipulate[
expr = Sqrt[R^2 - zeta^2] - zeta Tan[zeta];
zero = zeta /. NSolve[{expr == 0,
R^2 - zeta^2 >= 0}, zeta] // Quiet;
Column[{
Plot[expr, {zeta, -maxR, maxR},
Exclusions -> {Cos[zeta] == 0},
PlotRange -> {{-maxR, maxR}, {-25, 40}},
Epilog -> {Red, AbsolutePointSize[4],
Point[{#, 0} & /@ zero]},
AspectRatio -> 1],
zero},
Alignment -> Center],
{{R, Sqrt[18]}, 0, maxR, Appearance -> "Labeled"}]]
```
 | I'm going to guess that you're trying to solve for the even states of the finite square well in quantum mechanics. Note that the number of roots is just determined by $R$, and is `Floor[R/Ο]`; plot the graphs of $\zeta \tan \zeta$ and $\sqrt{R^2 - \zeta^2}$ to see why this is so. Moreover, it's not too hard from this graph to see that the first root will always be in the region $[0, \pi/2)$; the second root will be in the range $[\pi, 3\pi/2)$; the third will be in the range $[2\pi, 5\pi/2)$; and so forth.
`FindRoot` allows for an option where you can provide it with values $\{ x, x\_{start}, x\_{min}, x\_{max}\}$, which will search for a root within the interval $[x\_{min}, x\_{max}]$. Since we know where the roots are for this function, we can take advantage of this functionality like so:
```
nroots[R_] := Floor[R/\[Pi]] + 1;
roots[R_] := Table[FindRoot[Sqrt[R^2 - ΞΆ^2] - ΞΆ Tan[ΞΆ] == 0,
{ΞΆ, n Ο + Ο/4, n Ο, n Ο + Ο/2}], {n, 0, nroots[R] - 1}]
nroots[3β2]
(* {{ΞΆ -> 1.26743}, {ΞΆ -> 3.66808}} *)
```
The analogous problem for the odd-parity states is left as an exercise for the student. :-) |
80,649 | I am working on a physics reserach project for school and I have run into some troubles working Mathematica. I am a fairly inexperienced mathematica user so any help would very much be appreciated.
I need to find the roots of the transcendental equation
$$\zeta\_n \tan(\zeta) - \sqrt{R^2-\zeta^2\_n}=0$$
and then collect them into a list, $\{\zeta\_n\}$, which I can sum over.
FindRoot works but only finds one root at a time. For example $R^2=18$ gives
>
> FindRoot[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, {zeta, 3}]
>
>
> {zeta -> 3.66808}
> From a plot of the function I know there should be two roots for this particular value of $R$, however FindRoot only gives one.
>
>
>
I have had no luck with NSolve or Solve either.
>
> NSolve[xi[zeta, Erg4]- zeta\*Tan[zeta] == 0, zeta]
>
>
> NSolve[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, zeta]
>
>
>
Also once I have succeeded in finding all roots how does one put them in an indexed set ${\zeta\_n}$. | 2015/04/22 | [
"https://mathematica.stackexchange.com/questions/80649",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/27986/"
]
| ```
With[{maxR = 10},
Manipulate[
expr = Sqrt[R^2 - zeta^2] - zeta Tan[zeta];
zero = zeta /. NSolve[{expr == 0,
R^2 - zeta^2 >= 0}, zeta] // Quiet;
Column[{
Plot[expr, {zeta, -maxR, maxR},
Exclusions -> {Cos[zeta] == 0},
PlotRange -> {{-maxR, maxR}, {-25, 40}},
Epilog -> {Red, AbsolutePointSize[4],
Point[{#, 0} & /@ zero]},
AspectRatio -> 1],
zero},
Alignment -> Center],
{{R, Sqrt[18]}, 0, maxR, Appearance -> "Labeled"}]]
```
 | If you only want real solutions, then `NSolve` will find them if we help it by including the domain for `zeta`.
```
R = Sqrt[18];
sol = NSolve[Sqrt[R^2 - zeta^2] - zeta Tan[zeta] == 0 && -R <= zeta <= R]
(*
{{zeta -> -3.66808}, {zeta -> -1.26743},
{zeta -> 1.26743}, {zeta -> 3.66808}}
*)
```
You can save them in an indexed list like this:
```
roots = zeta /. sol
(* {-3.66808, -1.26743, 1.26743, 3.66808} *)
``` |
80,649 | I am working on a physics reserach project for school and I have run into some troubles working Mathematica. I am a fairly inexperienced mathematica user so any help would very much be appreciated.
I need to find the roots of the transcendental equation
$$\zeta\_n \tan(\zeta) - \sqrt{R^2-\zeta^2\_n}=0$$
and then collect them into a list, $\{\zeta\_n\}$, which I can sum over.
FindRoot works but only finds one root at a time. For example $R^2=18$ gives
>
> FindRoot[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, {zeta, 3}]
>
>
> {zeta -> 3.66808}
> From a plot of the function I know there should be two roots for this particular value of $R$, however FindRoot only gives one.
>
>
>
I have had no luck with NSolve or Solve either.
>
> NSolve[xi[zeta, Erg4]- zeta\*Tan[zeta] == 0, zeta]
>
>
> NSolve[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, zeta]
>
>
>
Also once I have succeeded in finding all roots how does one put them in an indexed set ${\zeta\_n}$. | 2015/04/22 | [
"https://mathematica.stackexchange.com/questions/80649",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/27986/"
]
| ```
With[{maxR = 10},
Manipulate[
expr = Sqrt[R^2 - zeta^2] - zeta Tan[zeta];
zero = zeta /. NSolve[{expr == 0,
R^2 - zeta^2 >= 0}, zeta] // Quiet;
Column[{
Plot[expr, {zeta, -maxR, maxR},
Exclusions -> {Cos[zeta] == 0},
PlotRange -> {{-maxR, maxR}, {-25, 40}},
Epilog -> {Red, AbsolutePointSize[4],
Point[{#, 0} & /@ zero]},
AspectRatio -> 1],
zero},
Alignment -> Center],
{{R, Sqrt[18]}, 0, maxR, Appearance -> "Labeled"}]]
```
 | After a slight rearrangement, your equation is a good candidate for the Chebyshev approach, as detailed [here](https://mathematica.stackexchange.com/a/89692) and [here](https://mathematica.stackexchange.com/a/92042):
```
r = Sqrt[18]; f = Sqrt[r^2 - #^2] Cos[#] - # Sin[#] &;
n = 32;
cnodes = Rescale[N[Cos[Pi Range[0, n]/n], 20], {-1, 1}, {-r, r}];
cc = Sqrt[2/n] FourierDCT[f /@ cnodes, 1];
cc[[{1, -1}]] /= 2;
colleague = SparseArray[{{i_, j_} /; i + 1 == j :> 1/2,
{i_, j_} /; i == j + 1 :> 1/(2 - Boole[j == 1])},
{n, n}] -
SparseArray[{{i_, n} :> cc[[i]]/(2 cc[[n + 1]])}, {n, n}];
rts = Sort[Select[DeleteCases[
Rescale[Eigenvalues[colleague], {-1, 1}, {-r, r}],
_Complex | _DirectedInfinity], Abs[#] <= r &]];
Plot[x Tan[x] - Sqrt[r^2 - x^2], {x, -r, r},
Epilog -> {Directive[Red, PointSize[Medium]],
Point[Transpose[PadRight[{rts}, {2, Automatic}]]]},
Exclusions -> {Cos[x] == 0}]
```
 |
80,649 | I am working on a physics reserach project for school and I have run into some troubles working Mathematica. I am a fairly inexperienced mathematica user so any help would very much be appreciated.
I need to find the roots of the transcendental equation
$$\zeta\_n \tan(\zeta) - \sqrt{R^2-\zeta^2\_n}=0$$
and then collect them into a list, $\{\zeta\_n\}$, which I can sum over.
FindRoot works but only finds one root at a time. For example $R^2=18$ gives
>
> FindRoot[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, {zeta, 3}]
>
>
> {zeta -> 3.66808}
> From a plot of the function I know there should be two roots for this particular value of $R$, however FindRoot only gives one.
>
>
>
I have had no luck with NSolve or Solve either.
>
> NSolve[xi[zeta, Erg4]- zeta\*Tan[zeta] == 0, zeta]
>
>
> NSolve[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, zeta]
>
>
>
Also once I have succeeded in finding all roots how does one put them in an indexed set ${\zeta\_n}$. | 2015/04/22 | [
"https://mathematica.stackexchange.com/questions/80649",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/27986/"
]
| If the goal is only to obtain the sum of positive roots, then
```
f[r_] := Total[ΞΆ /. NSolve[{Sqrt[r^2 - ΞΆ^2] - ΞΆ Tan[ΞΆ] == 0,
r^2 - ΞΆ^2 >= 0, ΞΆ > 0}, ΞΆ]]
```
produces this quantity. For instance,
```
Plot[f[r], {r, .1, 10}, AxesLabel -> {R, Total}]
```

`Quiet` is used only to suppress the occasional information message,
```
Solve::ratnz: Solve was unable to solve the system with inexact coefficients. The answer was obtained by solving a corresponding exact system and numericizing the result. >>
``` | If you only want real solutions, then `NSolve` will find them if we help it by including the domain for `zeta`.
```
R = Sqrt[18];
sol = NSolve[Sqrt[R^2 - zeta^2] - zeta Tan[zeta] == 0 && -R <= zeta <= R]
(*
{{zeta -> -3.66808}, {zeta -> -1.26743},
{zeta -> 1.26743}, {zeta -> 3.66808}}
*)
```
You can save them in an indexed list like this:
```
roots = zeta /. sol
(* {-3.66808, -1.26743, 1.26743, 3.66808} *)
``` |
80,649 | I am working on a physics reserach project for school and I have run into some troubles working Mathematica. I am a fairly inexperienced mathematica user so any help would very much be appreciated.
I need to find the roots of the transcendental equation
$$\zeta\_n \tan(\zeta) - \sqrt{R^2-\zeta^2\_n}=0$$
and then collect them into a list, $\{\zeta\_n\}$, which I can sum over.
FindRoot works but only finds one root at a time. For example $R^2=18$ gives
>
> FindRoot[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, {zeta, 3}]
>
>
> {zeta -> 3.66808}
> From a plot of the function I know there should be two roots for this particular value of $R$, however FindRoot only gives one.
>
>
>
I have had no luck with NSolve or Solve either.
>
> NSolve[xi[zeta, Erg4]- zeta\*Tan[zeta] == 0, zeta]
>
>
> NSolve[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, zeta]
>
>
>
Also once I have succeeded in finding all roots how does one put them in an indexed set ${\zeta\_n}$. | 2015/04/22 | [
"https://mathematica.stackexchange.com/questions/80649",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/27986/"
]
| I'm going to guess that you're trying to solve for the even states of the finite square well in quantum mechanics. Note that the number of roots is just determined by $R$, and is `Floor[R/Ο]`; plot the graphs of $\zeta \tan \zeta$ and $\sqrt{R^2 - \zeta^2}$ to see why this is so. Moreover, it's not too hard from this graph to see that the first root will always be in the region $[0, \pi/2)$; the second root will be in the range $[\pi, 3\pi/2)$; the third will be in the range $[2\pi, 5\pi/2)$; and so forth.
`FindRoot` allows for an option where you can provide it with values $\{ x, x\_{start}, x\_{min}, x\_{max}\}$, which will search for a root within the interval $[x\_{min}, x\_{max}]$. Since we know where the roots are for this function, we can take advantage of this functionality like so:
```
nroots[R_] := Floor[R/\[Pi]] + 1;
roots[R_] := Table[FindRoot[Sqrt[R^2 - ΞΆ^2] - ΞΆ Tan[ΞΆ] == 0,
{ΞΆ, n Ο + Ο/4, n Ο, n Ο + Ο/2}], {n, 0, nroots[R] - 1}]
nroots[3β2]
(* {{ΞΆ -> 1.26743}, {ΞΆ -> 3.66808}} *)
```
The analogous problem for the odd-parity states is left as an exercise for the student. :-) | If you only want real solutions, then `NSolve` will find them if we help it by including the domain for `zeta`.
```
R = Sqrt[18];
sol = NSolve[Sqrt[R^2 - zeta^2] - zeta Tan[zeta] == 0 && -R <= zeta <= R]
(*
{{zeta -> -3.66808}, {zeta -> -1.26743},
{zeta -> 1.26743}, {zeta -> 3.66808}}
*)
```
You can save them in an indexed list like this:
```
roots = zeta /. sol
(* {-3.66808, -1.26743, 1.26743, 3.66808} *)
``` |
80,649 | I am working on a physics reserach project for school and I have run into some troubles working Mathematica. I am a fairly inexperienced mathematica user so any help would very much be appreciated.
I need to find the roots of the transcendental equation
$$\zeta\_n \tan(\zeta) - \sqrt{R^2-\zeta^2\_n}=0$$
and then collect them into a list, $\{\zeta\_n\}$, which I can sum over.
FindRoot works but only finds one root at a time. For example $R^2=18$ gives
>
> FindRoot[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, {zeta, 3}]
>
>
> {zeta -> 3.66808}
> From a plot of the function I know there should be two roots for this particular value of $R$, however FindRoot only gives one.
>
>
>
I have had no luck with NSolve or Solve either.
>
> NSolve[xi[zeta, Erg4]- zeta\*Tan[zeta] == 0, zeta]
>
>
> NSolve[Sqrt[18. - zeta^2] - zeta Tan[zeta] == 0, zeta]
>
>
>
Also once I have succeeded in finding all roots how does one put them in an indexed set ${\zeta\_n}$. | 2015/04/22 | [
"https://mathematica.stackexchange.com/questions/80649",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/27986/"
]
| After a slight rearrangement, your equation is a good candidate for the Chebyshev approach, as detailed [here](https://mathematica.stackexchange.com/a/89692) and [here](https://mathematica.stackexchange.com/a/92042):
```
r = Sqrt[18]; f = Sqrt[r^2 - #^2] Cos[#] - # Sin[#] &;
n = 32;
cnodes = Rescale[N[Cos[Pi Range[0, n]/n], 20], {-1, 1}, {-r, r}];
cc = Sqrt[2/n] FourierDCT[f /@ cnodes, 1];
cc[[{1, -1}]] /= 2;
colleague = SparseArray[{{i_, j_} /; i + 1 == j :> 1/2,
{i_, j_} /; i == j + 1 :> 1/(2 - Boole[j == 1])},
{n, n}] -
SparseArray[{{i_, n} :> cc[[i]]/(2 cc[[n + 1]])}, {n, n}];
rts = Sort[Select[DeleteCases[
Rescale[Eigenvalues[colleague], {-1, 1}, {-r, r}],
_Complex | _DirectedInfinity], Abs[#] <= r &]];
Plot[x Tan[x] - Sqrt[r^2 - x^2], {x, -r, r},
Epilog -> {Directive[Red, PointSize[Medium]],
Point[Transpose[PadRight[{rts}, {2, Automatic}]]]},
Exclusions -> {Cos[x] == 0}]
```
 | If you only want real solutions, then `NSolve` will find them if we help it by including the domain for `zeta`.
```
R = Sqrt[18];
sol = NSolve[Sqrt[R^2 - zeta^2] - zeta Tan[zeta] == 0 && -R <= zeta <= R]
(*
{{zeta -> -3.66808}, {zeta -> -1.26743},
{zeta -> 1.26743}, {zeta -> 3.66808}}
*)
```
You can save them in an indexed list like this:
```
roots = zeta /. sol
(* {-3.66808, -1.26743, 1.26743, 3.66808} *)
``` |
65,126,618 | I have monthly data and I want to plot only certain regions, every 24 steps (2 years) or so, how can I find a quick way to plot every 20 steps using a for loop maybe?
For example, instead of doing this:
```
#first 24 indices
plt.plot(time_months[0:24], monthly[0:24])
plt.xticks(rotation=35)
plt.show()
#next set of 24 indices
plt.plot(time_months[24:48], monthly[24:48])
plt.xticks(rotation=35)
plt.show()
```
I tried this:
```
for i in range(monthly.size):
plt.plot(time_months[0:i,24])
plt.show()
```
but I get an error:
```
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-11-db04910853f1> in <module>
4
5 for i in range(monthly.size):
----> 6 plt.plot(time_months[0:24,i])
7 plt.show()
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
``` | 2020/12/03 | [
"https://Stackoverflow.com/questions/65126618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14714547/"
]
| `pipenv` has no special option for it. But you can use these bash scripts (I made them using the venvs directory `~/.local/share/virtualenvs/` so you should change it if your venvs folder is different)
PRINT useless venvs:
====================
```
for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do proj_path="$(cat $f)" && [ ! -d "$proj_path" ] && echo ${f//\/.project}; done;
```
**PRINT not existing projects paths** that still have corresponding venvs:
```
for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do proj_path="$(cat $f)" && [ ! -d "$proj_path" ] && echo $proj_path; done;
```
**PRINT both** (useless venvs and not existing project folders):
```
for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do proj_path="$(cat $f)" && [ ! -d "$proj_path" ] && echo $proj_path "\n"${f//\/.project} "\n"; done;
```
DELETE useless venvs
====================
```
for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do proj_path="$(cat $f)" && [ ! -d "$proj_path" ] && rm -rif ${f//\/.project} && echo DELETING ${f//\/.project}; done;
```
Try printing the venvs before deleting!
p.s. If your venv folder is not `~/.local/share/virtualenvs/`, make sure to change it to your venv path! | Here is a bash script to check and clean up abandoned pipenv environments interactively based on the [answer of @yestema](https://stackoverflow.com/a/67209898/12361118).
```sh
#!/usr/bin/env bash
# Author: TiDu Nguyen
# https://gist.github.com/tidunguyen/0fc018326f33c29e819be7f388360a5b
# get all pipenv environments
allPipenvEnv=$(find ~/.local/share/virtualenvs/*/.project -type f)
# find abandoned environments
abandonedEnv=()
for f in $allPipenvEnv; do
proj_path="$(cat $f)" && [ ! -d $proj_path ] && abandonedEnv+=($proj_path)
done
# if there is any abandoned environment, prompt for cleaning, else, exit
if [ ${#abandonedEnv[@]} -eq 0 ]; then
echo "No abandoned environment, hooray"
else
echo "Found ${#abandonedEnv[@]} abandoned pipenv environment(s):"
for value in "${abandonedEnv[@]}"; do
echo $value
done
echo -e "\nClean up abandoned pipenv environments?"
select choice in "Yes" "No"; do
case $choice in
Yes)
for f in $allPipenvEnv; do
proj_path="$(cat $f)" && [ ! -d $proj_path ] && rm -rif ${f//\/.project/} && echo DELETING ${f//\/.project/}
done
echo "Done!"
break
;;
No)
break
;;
esac
done
fi
``` |
65,126,618 | I have monthly data and I want to plot only certain regions, every 24 steps (2 years) or so, how can I find a quick way to plot every 20 steps using a for loop maybe?
For example, instead of doing this:
```
#first 24 indices
plt.plot(time_months[0:24], monthly[0:24])
plt.xticks(rotation=35)
plt.show()
#next set of 24 indices
plt.plot(time_months[24:48], monthly[24:48])
plt.xticks(rotation=35)
plt.show()
```
I tried this:
```
for i in range(monthly.size):
plt.plot(time_months[0:i,24])
plt.show()
```
but I get an error:
```
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-11-db04910853f1> in <module>
4
5 for i in range(monthly.size):
----> 6 plt.plot(time_months[0:24,i])
7 plt.show()
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
``` | 2020/12/03 | [
"https://Stackoverflow.com/questions/65126618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14714547/"
]
| `pipenv` has no special option for it. But you can use these bash scripts (I made them using the venvs directory `~/.local/share/virtualenvs/` so you should change it if your venvs folder is different)
PRINT useless venvs:
====================
```
for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do proj_path="$(cat $f)" && [ ! -d "$proj_path" ] && echo ${f//\/.project}; done;
```
**PRINT not existing projects paths** that still have corresponding venvs:
```
for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do proj_path="$(cat $f)" && [ ! -d "$proj_path" ] && echo $proj_path; done;
```
**PRINT both** (useless venvs and not existing project folders):
```
for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do proj_path="$(cat $f)" && [ ! -d "$proj_path" ] && echo $proj_path "\n"${f//\/.project} "\n"; done;
```
DELETE useless venvs
====================
```
for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do proj_path="$(cat $f)" && [ ! -d "$proj_path" ] && rm -rif ${f//\/.project} && echo DELETING ${f//\/.project}; done;
```
Try printing the venvs before deleting!
p.s. If your venv folder is not `~/.local/share/virtualenvs/`, make sure to change it to your venv path! | I built a function for this based on the [answer of @yestema](https://stackoverflow.com/a/67209898/15034335). You can check it in my [repo](https://github.com/tw-yshuang/Automatic-Installation_basic-Ubuntu-setting/blob/main/config/.customfunction).
Save the code below into your profile, e.q. ~/.bashrc .
```
# extra pipenv command
pipenv_correspond(){
local isDefault=true
local isLS=true
local isRM=false
local show_proj_root=true
local CORRESPOND=""
declare -a venvs_root_arr=()
local help_book='Usage: pipenv_correspond [OPTION]\n\nOPTION:
ls, --list list all the corresponding projects_root & venvs
uls, --useless list all the not existing projects_roots that still have correspondenting venvs
npr, --no-project-root hide projects_root
rm, --remove remove all the venvs from command: "ls" or "uls", deafult is use "uls"
'
function Show_root(){
declare -a venvs_arr=()
declare -i num_venvs=0
if $show_proj_root; then
for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do
proj_root="$(cat $f)" && [ $CORRESPOND -d $proj_root ] && echo "\nproj: $proj_root\nvenv: ${f//\/.project}\n" && venvs_root_arr+=(${f//\/.project}) && num_venvs+=1
done
else
for f in $(find ~/.local/share/virtualenvs/*/.project -type f); do
proj_root="$(cat $f)" && [ $CORRESPOND -d $proj_root ] && echo "${f//\/.project}\n" && venvs_root_arr+=(${f//\/.project}) && num_venvs+=1
done
fi
echo "Total venvs: $num_venvs"
}
if [ "$#" -gt 0 ]; then
while [ "$#" -gt 0 ]; do
case $1 in
"-h" | "--help" )
echo $help_book
return
;;
"ls" | "--list" )
isDefault=false
isLS=true
shift 1
;;
"uls" | "--useless" )
isDefault=false
isLS=false
shift 1
;;
"npr" | "--no-project-root" )
show_proj_root=false
shift 1
;;
"rm" | "--remove" )
isRM=true
shift 1
;;
*)
echo "\e[31mWrong command keyword!\e[0m"
return
;;
esac
done
fi
if ! $isLS || ( $isRM && $isDefault ); then
CORRESPOND="!"
echo "Useless venvs:"
else
echo "Still corresponding venvs:"
fi
Show_root venvs_root_arr
if $isRM; then
while ! $isDefault && $isLS; do
printf "\e[33mAre you sure you want to remove all venvs that still existing projects_roots?[y/n] \e[0m"
read respond
if [ "$respond" = "n" -o "$respond" = "N" ]; then
echo "bye~~~"
return
elif [ "$respond" != "y" -a "$respond" != "Y" ]; then
echo "Must type 'y' or 'n'!"
else
break
fi
done
echo $venvs_root_arr
echo "\e[33mWait...\e[0m"
for value in ${venvs_root_arr[@]}; do
echo "remving... $value"
rm -rf $value
done
echo "\e[32mSuccessflly removed all venvs!!\e[0m"
fi
}
``` |
1,897,672 | Let $f$ be a separable monic polynomials with integer coefficient. Let $K$ be the splitting field of $f$ over $\mathbb{Q}$, and let $p$ be a prime. What is the relationship between the statements
$f$ splits over $\mathbb{F}\_p$ and
$p$ is not irreducible in $K$ (there is probably some fancy term for this, like $p$ is inert in $K$?)
There are equivalent for the Gaussian Integers, so probably also for any quadratic extension with trivial class group.
I suspect they are equivalent, and this is probably extremely well known, but I have asked a couple people with no luck. | 2016/08/20 | [
"https://math.stackexchange.com/questions/1897672",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/116154/"
]
| Let $ K = \mathbf Q(\alpha) $ be a number field with ring of integers $ \mathcal O\_K $, where $ \alpha $ is an algebraic integer with minimal polynomial $ \pi(X)$. Dedekind's factorization criterion tells us that if $ p $ is a prime which does not divide the index $ [\mathcal O\_K : \mathbf Z[\alpha]] $, then the way $ \pi(X) $ splits modulo $ p $ is equivalent to the way $ (p) $ splits in $ \mathcal O\_K $, in other words, if we have
$$ (p) = \prod\_{i=1}^n \mathfrak p\_i^{e\_i} $$
in $ \mathcal O\_K $ where the inertia degrees of $ \mathfrak p\_i $ are $ f\_i $, then we have
$$ \pi(X) \equiv \prod\_{i=1}^n \pi\_i(X)^{e\_i} \pmod{p} $$
where the $ \pi\_i $ are irreducible in $ \mathbf Z/p\mathbf Z[X] $ with $ \deg \pi\_i = f\_i $. This is essentially a consequence of the isomorphisms
$$ \mathbf Z[\alpha]/(p) \cong \mathbf Z[X]/(\pi(X), p) \cong \mathbf Z/p \mathbf Z[X]/(\pi(X)) $$
and the fact that you can read off the relevant data from the ring structure alone. As an example of how this fails when the criterion regarding the index is not met, consider $ K = \mathbf Q(\sqrt{5}) $. $ \mathbf Z[\sqrt{5}] $ has index $ 2 $ in $ \mathcal O\_K $, and we have $ x^2 - 5 = (x+1)^2 $ in $ \mathbf Z/2\mathbf Z $, which suggests that $ 2 $ would be a totally ramified prime. However, this is not the case: $ \operatorname{disc} \mathcal O\_K = 5 $, therefore $ 2 $ is not even a ramified prime in $ \mathcal O\_K $. (This is a counterexample to your claim, since $ \mathbf Q(\sqrt{5}) $ is actually the splitting field of $ x^2 - 5 $ over $ \mathbf Q $. Note that $ \mathcal O\_K $ is even a principal ideal domain!) | Letβs look at a simple example, $f(X)=X^3-2$ and its splitting field $K=\Bbb Q(\lambda,\omega)$, over $\Bbb Q$, where $\lambda=\sqrt[3]2$ and $\omega$ is a primitive cube root of unity. Take $p=5$, and look at $f\in\Bbb F\_5[X]$, where it factors as $(X+2)(X^2+3X+4)$, so $f$ doesnβt split there.
Calling $\mathscr O$ the ring of algebraic integers of $K$, we can see that $5\mathscr O$ factors as $\mathfrak p\_1\mathfrak p\_2\mathfrak p\_3$, where in each case $\mathscr O/\mathfrak p\_i\cong\Bbb F\_{25}$. |
7,858 | My title sums up my question pretty well. We're investigating whether we can use a Kanban-based system to manage and track some internal projects and one of our requirements is to track time spent on activities. This will allow us to collect stats on engineering cost.
Is anyone doing this and if so, how? | 2012/10/18 | [
"https://pm.stackexchange.com/questions/7858",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4752/"
]
| ### TL;DR
Don't think "time tracking." Think "cycle time" instead.
### Kanban Should Measure Cycle Time
Generally, Kanban is not about measuring "activities" at a granular level; it is about measuring cycle time for a pull through the entire system. There is legitimate debate about whether this time should include lead time (e.g. time spent in the ice box) or just time from "started" to "done."
Some examples of how lead and cycle times can be measured are:
* [Kanban and When Will This Be Done?](https://web.archive.org/web/20160304145123/http://www.dennisstevens.com/2010/06/07/kanban-and-when-will-this-be-done/)
* [Kanban Analytics & Metrics: Lead and Cycle Time and Cumulative Flow Diagram](http://kanbantool.com/kanban-analytics-and-metrics)
but there may certainly be better explanations out there. The the general idea, though, is that you care about how long it takes and average batch to move from from initialization to a delivered state--regardless of how you choose to measure that.
### Don't Micro-Manage
The important thing in Kanban is that you are *not* measuring sub-tasks or work products belows the level of the user story. In other words, if a user story is "embiggen the quux" then it doesn't matter how long it takes to order the quux components, perform the embiggening, or update the quux documentation--unless those are explicit queues in your Kanban process, of course.
With Kanban, the question you're asking is "how long does it normally take for a standard-sized story to move through the entire queue and across all defined processes for that queue?" You then use *kaizen* to eliminate waste and reduce cycle time to the maximum extent practical, rather than optimizing individual tasks.
When you ask how to track time spent on specific activities, you're trying to optimize parts of a task. This is wrong. Consider the following quote:
>
> To optimize the whole, you must sub-optimize the parts...First, model the process by breaking it down into between five and nine sub-processes. Visualize each sub-process as an input hopper that sits on top of a black box. Inputs to the queue are dumped on top of the input hopper where they wait their turn. When the black box is ready to process the next item it grabs an input from the bottom of the stack, does whatever it does, and shoves it onto the top of the input hopper of the next sub-process.
>
>
> Lewis, Bob (2012-01-23). Keep the Joint Running: A Manifesto for 21st Century Information Technology (pp. 31-38). IS Survivor Publishing. Kindle Edition.
>
>
>
All you (should) care about is the overall efficiency of the entire process chain, not the individual sub-processes. That doesn't mean waste can't exist in a sub-process, but you should spend *zero* time on that level of analysis until and unless it is negatively impacting the cycle time of your macro-process. | I agree, that in general Kanban is not about tracking time spent on tasks. However, I understand a need for that. It seems to me that you need a virtual Kanban board with build-in time tracking and reports. The solution that offers such a powerful combination is [Kanban Tool](http://kanbantool.com/time-tracking). |
7,858 | My title sums up my question pretty well. We're investigating whether we can use a Kanban-based system to manage and track some internal projects and one of our requirements is to track time spent on activities. This will allow us to collect stats on engineering cost.
Is anyone doing this and if so, how? | 2012/10/18 | [
"https://pm.stackexchange.com/questions/7858",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4752/"
]
| I concur with [codegnome](https://pm.stackexchange.com/users/4271/codegnome "codegnome")'s answer above. Kanban is about outcomes, what the team delivers in terms of *throughput* and how fast they do this, measured as *cycle time*.
You could use this to support your financial analysis by asking 'Of our team's throughput, how much of that is bug fixes for product X, how much of it is new features for product X, new features for product Y etc?' and then charging your customer accordingly.
I would urge you to think in these terms rather than measuring developer activity as such measurements do not come for free, they are an imposition on the team and as such can end up being incorrectly recorded and so less than useful. | I agree, that in general Kanban is not about tracking time spent on tasks. However, I understand a need for that. It seems to me that you need a virtual Kanban board with build-in time tracking and reports. The solution that offers such a powerful combination is [Kanban Tool](http://kanbantool.com/time-tracking). |
7,858 | My title sums up my question pretty well. We're investigating whether we can use a Kanban-based system to manage and track some internal projects and one of our requirements is to track time spent on activities. This will allow us to collect stats on engineering cost.
Is anyone doing this and if so, how? | 2012/10/18 | [
"https://pm.stackexchange.com/questions/7858",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4752/"
]
| Disclaimer: I'm the author of Breeze.
I had a similar problem where I internally use Kanban for software development but still needed somehow to bill clients based on estimates and actual work done. So, being a developer, I made a simple tool called [Breeze](http://letsbreeze.com). It's basically a Kanban board with time tracking and reports. Initially I called it Trello and Basecamp hybrid with time tracking and reporting.
Basically you can add estimates and log work (also includes timer) for every card and you can then generate report based on that.
In an ideal world I would like to drop the tracking and use pure agile development but it is not possible if you are primarily doing freelance development. Also it really depends on the client, if they insist on Gantt charts then you are stuck. | I agree, that in general Kanban is not about tracking time spent on tasks. However, I understand a need for that. It seems to me that you need a virtual Kanban board with build-in time tracking and reports. The solution that offers such a powerful combination is [Kanban Tool](http://kanbantool.com/time-tracking). |
7,858 | My title sums up my question pretty well. We're investigating whether we can use a Kanban-based system to manage and track some internal projects and one of our requirements is to track time spent on activities. This will allow us to collect stats on engineering cost.
Is anyone doing this and if so, how? | 2012/10/18 | [
"https://pm.stackexchange.com/questions/7858",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4752/"
]
| ### TL;DR
Don't think "time tracking." Think "cycle time" instead.
### Kanban Should Measure Cycle Time
Generally, Kanban is not about measuring "activities" at a granular level; it is about measuring cycle time for a pull through the entire system. There is legitimate debate about whether this time should include lead time (e.g. time spent in the ice box) or just time from "started" to "done."
Some examples of how lead and cycle times can be measured are:
* [Kanban and When Will This Be Done?](https://web.archive.org/web/20160304145123/http://www.dennisstevens.com/2010/06/07/kanban-and-when-will-this-be-done/)
* [Kanban Analytics & Metrics: Lead and Cycle Time and Cumulative Flow Diagram](http://kanbantool.com/kanban-analytics-and-metrics)
but there may certainly be better explanations out there. The the general idea, though, is that you care about how long it takes and average batch to move from from initialization to a delivered state--regardless of how you choose to measure that.
### Don't Micro-Manage
The important thing in Kanban is that you are *not* measuring sub-tasks or work products belows the level of the user story. In other words, if a user story is "embiggen the quux" then it doesn't matter how long it takes to order the quux components, perform the embiggening, or update the quux documentation--unless those are explicit queues in your Kanban process, of course.
With Kanban, the question you're asking is "how long does it normally take for a standard-sized story to move through the entire queue and across all defined processes for that queue?" You then use *kaizen* to eliminate waste and reduce cycle time to the maximum extent practical, rather than optimizing individual tasks.
When you ask how to track time spent on specific activities, you're trying to optimize parts of a task. This is wrong. Consider the following quote:
>
> To optimize the whole, you must sub-optimize the parts...First, model the process by breaking it down into between five and nine sub-processes. Visualize each sub-process as an input hopper that sits on top of a black box. Inputs to the queue are dumped on top of the input hopper where they wait their turn. When the black box is ready to process the next item it grabs an input from the bottom of the stack, does whatever it does, and shoves it onto the top of the input hopper of the next sub-process.
>
>
> Lewis, Bob (2012-01-23). Keep the Joint Running: A Manifesto for 21st Century Information Technology (pp. 31-38). IS Survivor Publishing. Kindle Edition.
>
>
>
All you (should) care about is the overall efficiency of the entire process chain, not the individual sub-processes. That doesn't mean waste can't exist in a sub-process, but you should spend *zero* time on that level of analysis until and unless it is negatively impacting the cycle time of your macro-process. | I concur with [codegnome](https://pm.stackexchange.com/users/4271/codegnome "codegnome")'s answer above. Kanban is about outcomes, what the team delivers in terms of *throughput* and how fast they do this, measured as *cycle time*.
You could use this to support your financial analysis by asking 'Of our team's throughput, how much of that is bug fixes for product X, how much of it is new features for product X, new features for product Y etc?' and then charging your customer accordingly.
I would urge you to think in these terms rather than measuring developer activity as such measurements do not come for free, they are an imposition on the team and as such can end up being incorrectly recorded and so less than useful. |
7,858 | My title sums up my question pretty well. We're investigating whether we can use a Kanban-based system to manage and track some internal projects and one of our requirements is to track time spent on activities. This will allow us to collect stats on engineering cost.
Is anyone doing this and if so, how? | 2012/10/18 | [
"https://pm.stackexchange.com/questions/7858",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4752/"
]
| My advice is to use whatever time tracking system you currently have rather than add unnecessary bells/whistles to Kanban because:
* It will cost you less in terms of time, effort, training and dollars.
* It will avoid giving people one less thing to complain about when you implement Kanban, so acceptance of this change will be easier.
* It will avoid trying to graft on bells/whistles onto Kanban that at the end of the day may not work as well as your current system.
If you don't have a time tracking system already in place then I suggest that you get a good one that your accounting and HR teams can work with rather than try to graft something onto Kanban boards. The fact that you're asking if this can be done says to me that it isn't obvious that it can be done which means you should think twice about whether or not it should be done. | I agree, that in general Kanban is not about tracking time spent on tasks. However, I understand a need for that. It seems to me that you need a virtual Kanban board with build-in time tracking and reports. The solution that offers such a powerful combination is [Kanban Tool](http://kanbantool.com/time-tracking). |
7,858 | My title sums up my question pretty well. We're investigating whether we can use a Kanban-based system to manage and track some internal projects and one of our requirements is to track time spent on activities. This will allow us to collect stats on engineering cost.
Is anyone doing this and if so, how? | 2012/10/18 | [
"https://pm.stackexchange.com/questions/7858",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4752/"
]
| Disclaimer: I'm the author of Breeze.
I had a similar problem where I internally use Kanban for software development but still needed somehow to bill clients based on estimates and actual work done. So, being a developer, I made a simple tool called [Breeze](http://letsbreeze.com). It's basically a Kanban board with time tracking and reports. Initially I called it Trello and Basecamp hybrid with time tracking and reporting.
Basically you can add estimates and log work (also includes timer) for every card and you can then generate report based on that.
In an ideal world I would like to drop the tracking and use pure agile development but it is not possible if you are primarily doing freelance development. Also it really depends on the client, if they insist on Gantt charts then you are stuck. | I concur with [codegnome](https://pm.stackexchange.com/users/4271/codegnome "codegnome")'s answer above. Kanban is about outcomes, what the team delivers in terms of *throughput* and how fast they do this, measured as *cycle time*.
You could use this to support your financial analysis by asking 'Of our team's throughput, how much of that is bug fixes for product X, how much of it is new features for product X, new features for product Y etc?' and then charging your customer accordingly.
I would urge you to think in these terms rather than measuring developer activity as such measurements do not come for free, they are an imposition on the team and as such can end up being incorrectly recorded and so less than useful. |
7,858 | My title sums up my question pretty well. We're investigating whether we can use a Kanban-based system to manage and track some internal projects and one of our requirements is to track time spent on activities. This will allow us to collect stats on engineering cost.
Is anyone doing this and if so, how? | 2012/10/18 | [
"https://pm.stackexchange.com/questions/7858",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4752/"
]
| Disclaimer: I am related to Eylean board development
There is a precise match solution launched instead of Eylean which covers the idea of using both Cycle time and time tracking as part of Kanban System. If it is still relevant option you can consider reviewing [Teamhood](https://teamhood.com)
One more tool is [Eylean Board](http://www.eylean.com) - it is virtual board which offer both scrum and kanban tools. You can customize it anyway you like through a simple GUI. I have to say the board looks pretty nice and is very fluent with drag and drop everywhere. And of course it has cycle and lead time reports. One thing is that Eylean must be installed on client machine it is not a web app. | I concur with [codegnome](https://pm.stackexchange.com/users/4271/codegnome "codegnome")'s answer above. Kanban is about outcomes, what the team delivers in terms of *throughput* and how fast they do this, measured as *cycle time*.
You could use this to support your financial analysis by asking 'Of our team's throughput, how much of that is bug fixes for product X, how much of it is new features for product X, new features for product Y etc?' and then charging your customer accordingly.
I would urge you to think in these terms rather than measuring developer activity as such measurements do not come for free, they are an imposition on the team and as such can end up being incorrectly recorded and so less than useful. |
7,858 | My title sums up my question pretty well. We're investigating whether we can use a Kanban-based system to manage and track some internal projects and one of our requirements is to track time spent on activities. This will allow us to collect stats on engineering cost.
Is anyone doing this and if so, how? | 2012/10/18 | [
"https://pm.stackexchange.com/questions/7858",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4752/"
]
| ### TL;DR
Don't think "time tracking." Think "cycle time" instead.
### Kanban Should Measure Cycle Time
Generally, Kanban is not about measuring "activities" at a granular level; it is about measuring cycle time for a pull through the entire system. There is legitimate debate about whether this time should include lead time (e.g. time spent in the ice box) or just time from "started" to "done."
Some examples of how lead and cycle times can be measured are:
* [Kanban and When Will This Be Done?](https://web.archive.org/web/20160304145123/http://www.dennisstevens.com/2010/06/07/kanban-and-when-will-this-be-done/)
* [Kanban Analytics & Metrics: Lead and Cycle Time and Cumulative Flow Diagram](http://kanbantool.com/kanban-analytics-and-metrics)
but there may certainly be better explanations out there. The the general idea, though, is that you care about how long it takes and average batch to move from from initialization to a delivered state--regardless of how you choose to measure that.
### Don't Micro-Manage
The important thing in Kanban is that you are *not* measuring sub-tasks or work products belows the level of the user story. In other words, if a user story is "embiggen the quux" then it doesn't matter how long it takes to order the quux components, perform the embiggening, or update the quux documentation--unless those are explicit queues in your Kanban process, of course.
With Kanban, the question you're asking is "how long does it normally take for a standard-sized story to move through the entire queue and across all defined processes for that queue?" You then use *kaizen* to eliminate waste and reduce cycle time to the maximum extent practical, rather than optimizing individual tasks.
When you ask how to track time spent on specific activities, you're trying to optimize parts of a task. This is wrong. Consider the following quote:
>
> To optimize the whole, you must sub-optimize the parts...First, model the process by breaking it down into between five and nine sub-processes. Visualize each sub-process as an input hopper that sits on top of a black box. Inputs to the queue are dumped on top of the input hopper where they wait their turn. When the black box is ready to process the next item it grabs an input from the bottom of the stack, does whatever it does, and shoves it onto the top of the input hopper of the next sub-process.
>
>
> Lewis, Bob (2012-01-23). Keep the Joint Running: A Manifesto for 21st Century Information Technology (pp. 31-38). IS Survivor Publishing. Kindle Edition.
>
>
>
All you (should) care about is the overall efficiency of the entire process chain, not the individual sub-processes. That doesn't mean waste can't exist in a sub-process, but you should spend *zero* time on that level of analysis until and unless it is negatively impacting the cycle time of your macro-process. | You can achieve this using [JIRA](http://www.atlassian.com/software/jira/overview/) (which will manage your issues/bugs/backlog) and [Greenhopper](http://www.atlassian.com/software/greenhopper/overview/kanban) (which will handle the Kanban side of it). Devs (or PMs) can log work on the issues that they're working on but, as others have mentioned, it might not be quite right in a Kanban context.
We use it in Scrum, where it's helpful for calculating burndown and velocity, but I should emphasize that, for us, it's just about helping us to improve our estimation and not overloading our sprints rather than for performance management. In my opinion, performance management is much more complex than just the measurement of hours/days a person has logged against a particular task. |
7,858 | My title sums up my question pretty well. We're investigating whether we can use a Kanban-based system to manage and track some internal projects and one of our requirements is to track time spent on activities. This will allow us to collect stats on engineering cost.
Is anyone doing this and if so, how? | 2012/10/18 | [
"https://pm.stackexchange.com/questions/7858",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4752/"
]
| You can achieve this using [JIRA](http://www.atlassian.com/software/jira/overview/) (which will manage your issues/bugs/backlog) and [Greenhopper](http://www.atlassian.com/software/greenhopper/overview/kanban) (which will handle the Kanban side of it). Devs (or PMs) can log work on the issues that they're working on but, as others have mentioned, it might not be quite right in a Kanban context.
We use it in Scrum, where it's helpful for calculating burndown and velocity, but I should emphasize that, for us, it's just about helping us to improve our estimation and not overloading our sprints rather than for performance management. In my opinion, performance management is much more complex than just the measurement of hours/days a person has logged against a particular task. | I concur with [codegnome](https://pm.stackexchange.com/users/4271/codegnome "codegnome")'s answer above. Kanban is about outcomes, what the team delivers in terms of *throughput* and how fast they do this, measured as *cycle time*.
You could use this to support your financial analysis by asking 'Of our team's throughput, how much of that is bug fixes for product X, how much of it is new features for product X, new features for product Y etc?' and then charging your customer accordingly.
I would urge you to think in these terms rather than measuring developer activity as such measurements do not come for free, they are an imposition on the team and as such can end up being incorrectly recorded and so less than useful. |
7,858 | My title sums up my question pretty well. We're investigating whether we can use a Kanban-based system to manage and track some internal projects and one of our requirements is to track time spent on activities. This will allow us to collect stats on engineering cost.
Is anyone doing this and if so, how? | 2012/10/18 | [
"https://pm.stackexchange.com/questions/7858",
"https://pm.stackexchange.com",
"https://pm.stackexchange.com/users/4752/"
]
| Disclaimer: I am related to Eylean board development
There is a precise match solution launched instead of Eylean which covers the idea of using both Cycle time and time tracking as part of Kanban System. If it is still relevant option you can consider reviewing [Teamhood](https://teamhood.com)
One more tool is [Eylean Board](http://www.eylean.com) - it is virtual board which offer both scrum and kanban tools. You can customize it anyway you like through a simple GUI. I have to say the board looks pretty nice and is very fluent with drag and drop everywhere. And of course it has cycle and lead time reports. One thing is that Eylean must be installed on client machine it is not a web app. | I agree, that in general Kanban is not about tracking time spent on tasks. However, I understand a need for that. It seems to me that you need a virtual Kanban board with build-in time tracking and reports. The solution that offers such a powerful combination is [Kanban Tool](http://kanbantool.com/time-tracking). |
8,859,384 | Is there such a thing as a 64-bit .dll for the YAJSW Java service wrapper? If so, where do I find it? I know that the Tanuki JSW provides .dll files that go with the .jar files it distributes. So, I am basically wondering if YAJSW has overcome this limitation and I dont need a .dll OR if I need to download one from somewhere?
The [YAJSW website](http://yajsw.sourceforge.net/YAJSW%20Configuration%20Parameters.html) mentions the existence of a w86.dll file but provides no information on where to find it or whether you need it or not. | 2012/01/14 | [
"https://Stackoverflow.com/questions/8859384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118228/"
]
| I think you are misunderstanding that reference to "w86.dll". I think it is supposed to be an example of some 3rd party application specific DLL. The text is about how to configure YAJSW to deal with such things.
I've never tried to use YAJSW, but the indications from the documentation is that 64 bit is supported for Windows. It should "just work" if you follow the generic instructions. Have you tried that? | You can find a list of supported platforms for YAJSW [here](http://yajsw.sourceforge.net/#mozTocId768274).
YAJSW distribution comes with what you need to get it running so as long as you are on a supported platform you should be good to go. |
18,667,510 | I have a bunch of directories that I need to restructure. They're in a format as such:
```
./1993-02-22 - The Moon - Tallahassee, FL/**files**
./1993-02-23 - The Moon - Tallahassee, FL/**files**
./1993-02-24 - The Moon - Tallahassee, FL/**files**
./1993-02-25 - The Moon - Tallahassee, FL/**files**
./1993-03-01 - The Test - Null, FL/**files**
```
I want to extract the dates from the beginning of each folder. For example, in regex: `([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})` and reformat the directories to `./year/month/day`.
So, it should output:
```
./1993/02/22/**files**
./1993/02/23/**files**
./1993/02/24/**files**
./1993/02/25/**files**
./1993/03/01/**files**
```
How can I go about doing that from a command line? | 2013/09/06 | [
"https://Stackoverflow.com/questions/18667510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240569/"
]
| I understood the question in a different way than [Kent](https://stackoverflow.com/users/164835/kent). I thought that you wanted to create a new tree of directories from each original one and move all files that it contained. You could try following [perl](/questions/tagged/perl "show questions tagged 'perl'") script if that was what you were looking for:
```
perl -MFile::Path=make_path -MFile::Copy=move -e '
for ( grep { -d } @ARGV ) {
@date = m/\A(\d{4})-(\d{2})-(\d{2})/;
next unless @date;
$outdir = join q{/}, @date;
make_path( $outdir );
move( $_, $outdir );
}
' *
```
It reads every file from current directory (`*` passed as argument) and does two step filter. The first one is the `grep` for no-directories files and the second one is an undefined `@date` for those that don't begin with it. Then it joins date's components into a path, creates it if doesn't exist and move the old one with all its files to the new one.
A test:
Here the result of `ls -lR` to show initial state:
```
.:
total 24
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 1993-02-22 - The Moon - Tallahassee, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 1993-02-23 - The Moon - Tallahassee, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 1993-02-24 - The Moon - Tallahassee, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 1993-02-25 - The Moon - Tallahassee, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 1993-03-01 - The Test - Null, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:47 dummy_dir
-rw-r--r-- 1 dcg dcg 0 sep 7 00:47 dummy_file
./1993-02-22 - The Moon - Tallahassee, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file1
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file2
./1993-02-23 - The Moon - Tallahassee, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file3
./1993-02-24 - The Moon - Tallahassee, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file4
./1993-02-25 - The Moon - Tallahassee, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file5
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file6
./1993-03-01 - The Test - Null, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file7
./dummy_dir:
total 0
```
And after running the previous script note that the base directory only keeps dummy files and the root of the tree created (`1993`). Running the same `ls -lR` yields:
```
.:
total 8
drwxr-xr-x 4 dcg dcg 4096 sep 7 00:59 1993
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:47 dummy_dir
-rw-r--r-- 1 dcg dcg 0 sep 7 00:47 dummy_file
./1993:
total 8
drwxr-xr-x 6 dcg dcg 4096 sep 7 00:59 02
drwxr-xr-x 3 dcg dcg 4096 sep 7 00:59 03
./1993/02:
total 16
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 22
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 23
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 24
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 25
./1993/02/22:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file1
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file2
./1993/02/23:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file3
./1993/02/24:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file4
./1993/02/25:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file5
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file6
./1993/03:
total 4
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 01
./1993/03/01:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file7
./dummy_dir:
total 0
``` | like this?
```
kent$ awk '{gsub(/-/,"/",$1);sub(/^[^/]*\//,"/",$NF);print $1$NF}' file
./1993/02/22/**files**
./1993/02/23/**files**
./1993/02/24/**files**
./1993/02/25/**files**
./1993/03/01/**files**
``` |
18,667,510 | I have a bunch of directories that I need to restructure. They're in a format as such:
```
./1993-02-22 - The Moon - Tallahassee, FL/**files**
./1993-02-23 - The Moon - Tallahassee, FL/**files**
./1993-02-24 - The Moon - Tallahassee, FL/**files**
./1993-02-25 - The Moon - Tallahassee, FL/**files**
./1993-03-01 - The Test - Null, FL/**files**
```
I want to extract the dates from the beginning of each folder. For example, in regex: `([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})` and reformat the directories to `./year/month/day`.
So, it should output:
```
./1993/02/22/**files**
./1993/02/23/**files**
./1993/02/24/**files**
./1993/02/25/**files**
./1993/03/01/**files**
```
How can I go about doing that from a command line? | 2013/09/06 | [
"https://Stackoverflow.com/questions/18667510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240569/"
]
| Suppose your files are stored in "old" folder, then you may write a shell script (avoid using "for" loop that has difficulties with file names containing spaces):
```
mkdir -p new
ls -d -1 old/*/* | while read oldfile; do
newfile=`echo "$oldfile" | sed -r 's#^old/([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})(.*)$#new/\1/\2/\3/\4#'`
newdir=` echo $newfile | sed 's#/[^/]*$##'`
echo "Creating \"$newdir\""
mkdir -p "$newdir"
echo "Moving files from \"$oldfile\" to \"$newfile\""
cp -r "$oldfile" "$newfile"
done
```
output of script:
```
Creating "new/1993/02/22/ - The Moon - Tallahassee, FL"
Moving files from "old/1993-02-22 - The Moon - Tallahassee, FL/test" to "new/1993/02/22/ - The Moon - Tallahassee, FL/test"
Creating "new/1993/02/23/ - The Moon - Tallahassee, FL"
Moving files from "old/1993-02-23 - The Moon - Tallahassee, FL/test" to "new/1993/02/23/ - The Moon - Tallahassee, FL/test"
Creating "new/1993/02/24/ - The Moon - Tallahassee, FL"
Moving files from "old/1993-02-24 - The Moon - Tallahassee, FL/test" to "new/1993/02/24/ - The Moon - Tallahassee, FL/test"
Creating "new/1993/02/25/ - The Moon - Tallahassee, FL"
Moving files from "old/1993-02-25 - The Moon - Tallahassee, FL/test" to "new/1993/02/25/ - The Moon - Tallahassee, FL/test"
Creating "new/1993/03/01/ - The Tes - Null, FL"
Moving files from "old/1993-03-01 - The Tes - Null, FL/test2" to "new/1993/03/01/ - The Tes - Null, FL/test2"
```
and you'll find your new tree in ... the "new" folder indeed:
```
$ tree old new
old
βββ 1993-02-22 - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 1993-02-23 - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 1993-02-24 - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 1993-02-25 - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 1993-03-01 - The Tes - Null, FL
βββ test2
new
βββ 1993
βββ 02
βΒ Β βββ 22
βΒ Β βΒ Β βββ - The Moon - Tallahassee, FL
βΒ Β βΒ Β βββ test
βΒ Β βββ 23
βΒ Β βΒ Β βββ - The Moon - Tallahassee, FL
βΒ Β βΒ Β βββ test
βΒ Β βββ 24
βΒ Β βΒ Β βββ - The Moon - Tallahassee, FL
βΒ Β βΒ Β βββ test
βΒ Β βββ 25
βΒ Β βββ - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 03
βββ 01
βββ - The Tes - Null, FL
βββ test2
``` | like this?
```
kent$ awk '{gsub(/-/,"/",$1);sub(/^[^/]*\//,"/",$NF);print $1$NF}' file
./1993/02/22/**files**
./1993/02/23/**files**
./1993/02/24/**files**
./1993/02/25/**files**
./1993/03/01/**files**
``` |
18,667,510 | I have a bunch of directories that I need to restructure. They're in a format as such:
```
./1993-02-22 - The Moon - Tallahassee, FL/**files**
./1993-02-23 - The Moon - Tallahassee, FL/**files**
./1993-02-24 - The Moon - Tallahassee, FL/**files**
./1993-02-25 - The Moon - Tallahassee, FL/**files**
./1993-03-01 - The Test - Null, FL/**files**
```
I want to extract the dates from the beginning of each folder. For example, in regex: `([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})` and reformat the directories to `./year/month/day`.
So, it should output:
```
./1993/02/22/**files**
./1993/02/23/**files**
./1993/02/24/**files**
./1993/02/25/**files**
./1993/03/01/**files**
```
How can I go about doing that from a command line? | 2013/09/06 | [
"https://Stackoverflow.com/questions/18667510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240569/"
]
| I understood the question in a different way than [Kent](https://stackoverflow.com/users/164835/kent). I thought that you wanted to create a new tree of directories from each original one and move all files that it contained. You could try following [perl](/questions/tagged/perl "show questions tagged 'perl'") script if that was what you were looking for:
```
perl -MFile::Path=make_path -MFile::Copy=move -e '
for ( grep { -d } @ARGV ) {
@date = m/\A(\d{4})-(\d{2})-(\d{2})/;
next unless @date;
$outdir = join q{/}, @date;
make_path( $outdir );
move( $_, $outdir );
}
' *
```
It reads every file from current directory (`*` passed as argument) and does two step filter. The first one is the `grep` for no-directories files and the second one is an undefined `@date` for those that don't begin with it. Then it joins date's components into a path, creates it if doesn't exist and move the old one with all its files to the new one.
A test:
Here the result of `ls -lR` to show initial state:
```
.:
total 24
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 1993-02-22 - The Moon - Tallahassee, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 1993-02-23 - The Moon - Tallahassee, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 1993-02-24 - The Moon - Tallahassee, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 1993-02-25 - The Moon - Tallahassee, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 1993-03-01 - The Test - Null, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:47 dummy_dir
-rw-r--r-- 1 dcg dcg 0 sep 7 00:47 dummy_file
./1993-02-22 - The Moon - Tallahassee, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file1
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file2
./1993-02-23 - The Moon - Tallahassee, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file3
./1993-02-24 - The Moon - Tallahassee, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file4
./1993-02-25 - The Moon - Tallahassee, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file5
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file6
./1993-03-01 - The Test - Null, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file7
./dummy_dir:
total 0
```
And after running the previous script note that the base directory only keeps dummy files and the root of the tree created (`1993`). Running the same `ls -lR` yields:
```
.:
total 8
drwxr-xr-x 4 dcg dcg 4096 sep 7 00:59 1993
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:47 dummy_dir
-rw-r--r-- 1 dcg dcg 0 sep 7 00:47 dummy_file
./1993:
total 8
drwxr-xr-x 6 dcg dcg 4096 sep 7 00:59 02
drwxr-xr-x 3 dcg dcg 4096 sep 7 00:59 03
./1993/02:
total 16
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 22
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 23
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 24
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 25
./1993/02/22:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file1
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file2
./1993/02/23:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file3
./1993/02/24:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file4
./1993/02/25:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file5
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file6
./1993/03:
total 4
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 01
./1993/03/01:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file7
./dummy_dir:
total 0
``` | Here is a `sed+awk` after so much of comments :
```
awk 'BEGIN{FS="-"}{print $1"/"$2"/"$3}' file | awk 'BEGIN{FS="**files**"}{print $1"/"FS}' | sed -e 's/ \//\//g'
./1993/02/22/**files**
./1993/02/23/**files**
./1993/02/24/**files**
./1993/02/25/**files**
./1993/03/01/**files**
``` |
18,667,510 | I have a bunch of directories that I need to restructure. They're in a format as such:
```
./1993-02-22 - The Moon - Tallahassee, FL/**files**
./1993-02-23 - The Moon - Tallahassee, FL/**files**
./1993-02-24 - The Moon - Tallahassee, FL/**files**
./1993-02-25 - The Moon - Tallahassee, FL/**files**
./1993-03-01 - The Test - Null, FL/**files**
```
I want to extract the dates from the beginning of each folder. For example, in regex: `([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})` and reformat the directories to `./year/month/day`.
So, it should output:
```
./1993/02/22/**files**
./1993/02/23/**files**
./1993/02/24/**files**
./1993/02/25/**files**
./1993/03/01/**files**
```
How can I go about doing that from a command line? | 2013/09/06 | [
"https://Stackoverflow.com/questions/18667510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240569/"
]
| Suppose your files are stored in "old" folder, then you may write a shell script (avoid using "for" loop that has difficulties with file names containing spaces):
```
mkdir -p new
ls -d -1 old/*/* | while read oldfile; do
newfile=`echo "$oldfile" | sed -r 's#^old/([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})(.*)$#new/\1/\2/\3/\4#'`
newdir=` echo $newfile | sed 's#/[^/]*$##'`
echo "Creating \"$newdir\""
mkdir -p "$newdir"
echo "Moving files from \"$oldfile\" to \"$newfile\""
cp -r "$oldfile" "$newfile"
done
```
output of script:
```
Creating "new/1993/02/22/ - The Moon - Tallahassee, FL"
Moving files from "old/1993-02-22 - The Moon - Tallahassee, FL/test" to "new/1993/02/22/ - The Moon - Tallahassee, FL/test"
Creating "new/1993/02/23/ - The Moon - Tallahassee, FL"
Moving files from "old/1993-02-23 - The Moon - Tallahassee, FL/test" to "new/1993/02/23/ - The Moon - Tallahassee, FL/test"
Creating "new/1993/02/24/ - The Moon - Tallahassee, FL"
Moving files from "old/1993-02-24 - The Moon - Tallahassee, FL/test" to "new/1993/02/24/ - The Moon - Tallahassee, FL/test"
Creating "new/1993/02/25/ - The Moon - Tallahassee, FL"
Moving files from "old/1993-02-25 - The Moon - Tallahassee, FL/test" to "new/1993/02/25/ - The Moon - Tallahassee, FL/test"
Creating "new/1993/03/01/ - The Tes - Null, FL"
Moving files from "old/1993-03-01 - The Tes - Null, FL/test2" to "new/1993/03/01/ - The Tes - Null, FL/test2"
```
and you'll find your new tree in ... the "new" folder indeed:
```
$ tree old new
old
βββ 1993-02-22 - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 1993-02-23 - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 1993-02-24 - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 1993-02-25 - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 1993-03-01 - The Tes - Null, FL
βββ test2
new
βββ 1993
βββ 02
βΒ Β βββ 22
βΒ Β βΒ Β βββ - The Moon - Tallahassee, FL
βΒ Β βΒ Β βββ test
βΒ Β βββ 23
βΒ Β βΒ Β βββ - The Moon - Tallahassee, FL
βΒ Β βΒ Β βββ test
βΒ Β βββ 24
βΒ Β βΒ Β βββ - The Moon - Tallahassee, FL
βΒ Β βΒ Β βββ test
βΒ Β βββ 25
βΒ Β βββ - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 03
βββ 01
βββ - The Tes - Null, FL
βββ test2
``` | Here is a `sed+awk` after so much of comments :
```
awk 'BEGIN{FS="-"}{print $1"/"$2"/"$3}' file | awk 'BEGIN{FS="**files**"}{print $1"/"FS}' | sed -e 's/ \//\//g'
./1993/02/22/**files**
./1993/02/23/**files**
./1993/02/24/**files**
./1993/02/25/**files**
./1993/03/01/**files**
``` |
18,667,510 | I have a bunch of directories that I need to restructure. They're in a format as such:
```
./1993-02-22 - The Moon - Tallahassee, FL/**files**
./1993-02-23 - The Moon - Tallahassee, FL/**files**
./1993-02-24 - The Moon - Tallahassee, FL/**files**
./1993-02-25 - The Moon - Tallahassee, FL/**files**
./1993-03-01 - The Test - Null, FL/**files**
```
I want to extract the dates from the beginning of each folder. For example, in regex: `([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})` and reformat the directories to `./year/month/day`.
So, it should output:
```
./1993/02/22/**files**
./1993/02/23/**files**
./1993/02/24/**files**
./1993/02/25/**files**
./1993/03/01/**files**
```
How can I go about doing that from a command line? | 2013/09/06 | [
"https://Stackoverflow.com/questions/18667510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240569/"
]
| I understood the question in a different way than [Kent](https://stackoverflow.com/users/164835/kent). I thought that you wanted to create a new tree of directories from each original one and move all files that it contained. You could try following [perl](/questions/tagged/perl "show questions tagged 'perl'") script if that was what you were looking for:
```
perl -MFile::Path=make_path -MFile::Copy=move -e '
for ( grep { -d } @ARGV ) {
@date = m/\A(\d{4})-(\d{2})-(\d{2})/;
next unless @date;
$outdir = join q{/}, @date;
make_path( $outdir );
move( $_, $outdir );
}
' *
```
It reads every file from current directory (`*` passed as argument) and does two step filter. The first one is the `grep` for no-directories files and the second one is an undefined `@date` for those that don't begin with it. Then it joins date's components into a path, creates it if doesn't exist and move the old one with all its files to the new one.
A test:
Here the result of `ls -lR` to show initial state:
```
.:
total 24
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 1993-02-22 - The Moon - Tallahassee, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 1993-02-23 - The Moon - Tallahassee, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 1993-02-24 - The Moon - Tallahassee, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 1993-02-25 - The Moon - Tallahassee, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 1993-03-01 - The Test - Null, FL
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:47 dummy_dir
-rw-r--r-- 1 dcg dcg 0 sep 7 00:47 dummy_file
./1993-02-22 - The Moon - Tallahassee, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file1
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file2
./1993-02-23 - The Moon - Tallahassee, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file3
./1993-02-24 - The Moon - Tallahassee, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file4
./1993-02-25 - The Moon - Tallahassee, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file5
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file6
./1993-03-01 - The Test - Null, FL:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file7
./dummy_dir:
total 0
```
And after running the previous script note that the base directory only keeps dummy files and the root of the tree created (`1993`). Running the same `ls -lR` yields:
```
.:
total 8
drwxr-xr-x 4 dcg dcg 4096 sep 7 00:59 1993
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:47 dummy_dir
-rw-r--r-- 1 dcg dcg 0 sep 7 00:47 dummy_file
./1993:
total 8
drwxr-xr-x 6 dcg dcg 4096 sep 7 00:59 02
drwxr-xr-x 3 dcg dcg 4096 sep 7 00:59 03
./1993/02:
total 16
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 22
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 23
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:56 24
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 25
./1993/02/22:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file1
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file2
./1993/02/23:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file3
./1993/02/24:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:56 file4
./1993/02/25:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file5
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file6
./1993/03:
total 4
drwxr-xr-x 2 dcg dcg 4096 sep 7 00:57 01
./1993/03/01:
total 0
-rw-r--r-- 1 dcg dcg 0 sep 7 00:57 file7
./dummy_dir:
total 0
``` | Suppose your files are stored in "old" folder, then you may write a shell script (avoid using "for" loop that has difficulties with file names containing spaces):
```
mkdir -p new
ls -d -1 old/*/* | while read oldfile; do
newfile=`echo "$oldfile" | sed -r 's#^old/([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})(.*)$#new/\1/\2/\3/\4#'`
newdir=` echo $newfile | sed 's#/[^/]*$##'`
echo "Creating \"$newdir\""
mkdir -p "$newdir"
echo "Moving files from \"$oldfile\" to \"$newfile\""
cp -r "$oldfile" "$newfile"
done
```
output of script:
```
Creating "new/1993/02/22/ - The Moon - Tallahassee, FL"
Moving files from "old/1993-02-22 - The Moon - Tallahassee, FL/test" to "new/1993/02/22/ - The Moon - Tallahassee, FL/test"
Creating "new/1993/02/23/ - The Moon - Tallahassee, FL"
Moving files from "old/1993-02-23 - The Moon - Tallahassee, FL/test" to "new/1993/02/23/ - The Moon - Tallahassee, FL/test"
Creating "new/1993/02/24/ - The Moon - Tallahassee, FL"
Moving files from "old/1993-02-24 - The Moon - Tallahassee, FL/test" to "new/1993/02/24/ - The Moon - Tallahassee, FL/test"
Creating "new/1993/02/25/ - The Moon - Tallahassee, FL"
Moving files from "old/1993-02-25 - The Moon - Tallahassee, FL/test" to "new/1993/02/25/ - The Moon - Tallahassee, FL/test"
Creating "new/1993/03/01/ - The Tes - Null, FL"
Moving files from "old/1993-03-01 - The Tes - Null, FL/test2" to "new/1993/03/01/ - The Tes - Null, FL/test2"
```
and you'll find your new tree in ... the "new" folder indeed:
```
$ tree old new
old
βββ 1993-02-22 - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 1993-02-23 - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 1993-02-24 - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 1993-02-25 - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 1993-03-01 - The Tes - Null, FL
βββ test2
new
βββ 1993
βββ 02
βΒ Β βββ 22
βΒ Β βΒ Β βββ - The Moon - Tallahassee, FL
βΒ Β βΒ Β βββ test
βΒ Β βββ 23
βΒ Β βΒ Β βββ - The Moon - Tallahassee, FL
βΒ Β βΒ Β βββ test
βΒ Β βββ 24
βΒ Β βΒ Β βββ - The Moon - Tallahassee, FL
βΒ Β βΒ Β βββ test
βΒ Β βββ 25
βΒ Β βββ - The Moon - Tallahassee, FL
βΒ Β βββ test
βββ 03
βββ 01
βββ - The Tes - Null, FL
βββ test2
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.