qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
14,803,197 | I'm currently building a web-server which can receive request, and send back a response.
I've managed to embed a port of Google's v8 JavaScript engine to c# (javascript.net) to my project and I want to parse a requested file and run the server-sided JavaScript code that in it. I decided that this code will be contained inside a 2-character brackets, <: for opening and :> for closing. I started to parse it with code I written but after encountering some problems which made the code more messy and probably not very efficient I decided to go ahead and try using RegEx (I had you study it because I've never used it before). BUT WAIT. After talking to my friend about it he send me this post [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) I understood that it isn't a good idea...
So my question is, How do I parse such thing? (Taking efficiency and clean code into account, after all it's a webserver).
Thanks in advance! | 2013/02/10 | [
"https://Stackoverflow.com/questions/14803197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319084/"
] | Yes, in Oracle SQL Developer put the statement:
```
SET SERVEROUTPUT ON;
```
just before your `DECLARE` keyword and this should work.
I couldn't find `View -> DBMS Output` and I'm using version 1.5.5. | ```
**SET SERVEROUTPUT ON;**
DECLARE
a INTEGER :=10;
b INTEGER :=20;
c float ;
d real ;
BEGIN
c :=a+b;
dbms_output.put_line('the value of C is :'|| c);
d := 70.0/3.3;
dbms_output.put_line('the value of d is:'|| d);
END;
```
This will give you the output
```
the value of C is: 30
the value of d is: 21.21212121212121212121212121212121212121
``` |
50,694,824 | I am using Notification Extension in my application to change the notification sound.
When the user turns off the `UISwitch` in the settings page I save in the `NSUserDefaults` a `boolean` to keep tracking of the state.
However I have 2 different storyboards for two different languages, each has its own style.
When I am using the storyboard A and I print the state of the `boolean` in the console, it's printing the state correctly. But when I change the language hence a different storyboard B loads up. The `boolean` is always returning `false`.
Although the boolean always return `false`, I have tested the sound of the notification, it works correctly.
Any idea why the `boolean` is always returning `false`? I need the correct value in order to show the state correctly of the ringtone in the settings page.
Here's the code I am using:
```
- (void)setPlayDefaultSound:(BOOL)playDefaultSound
{
NSUserDefaults *def = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.xx.xxx.NotificationServices"];
[def setBool:playDefaultSound forKey:@"playDefaultSound"];
[def synchronize];
}
- (BOOL)playDefaultSound
{
NSUserDefaults *def = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.xx.xxx.NotificationServices"];
return [def boolForKey:@"playDefaultSound"];
}
```
And here's a screenshot of the Info.plist of the Notification Services Extension:
[](https://i.stack.imgur.com/daewF.png) | 2018/06/05 | [
"https://Stackoverflow.com/questions/50694824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6532217/"
] | You may copy it from old Xcode(9.4). It should work.
```
cp /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/lib/libstdc++.* /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/lib/
cp /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/lib/libstdc++.* /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/lib/
``` | Copy it from old Xcode(9.4) will work for physical iOS devices.
For Simulator issues with `Did find: /usr/lib/libstdc++.6.dylib: mach-o, but not built for iOS simulator`. Looks like apple removed compatibility support for simulator. Just download iOS 11.4 simulator and it can be run on it. |
708,547 | My NVIDIA Control Panel seem to have a lack of settings other than the 3D Settings;

I searched around a bit and found some similar problems on other websites which seemed to either have solutions that didn't work, or no replies at all.
I have a nVidia Geforce 710m and I'm on Windows 8.1 however the problem also occurred before 8.1 on 8, I re-updated a few minutes ago to the latest drivers for my GPU and OS (332.21) and the problem is still there.
Any help would be much appreciated. | 2014/01/29 | [
"https://superuser.com/questions/708547",
"https://superuser.com",
"https://superuser.com/users/148401/"
] | The Intel integrated graphics adapter in your computer is most probably
the source of the problem.
The thread [Force 4:3 ratio / pillarbox with 540M](https://forums.geforce.com/default/topic/526745/force-4-3-ratio-pillarbox-with-540m/?offset=8) explains it :
>
> Your "problem" is not a problem at all but its the nature of your
> machine. You have an "Optimus" system which means you have an intel
> graphics processor and an Nvidia.
>
>
> You do not have the option in the Nvidia control panel since the intel
> driver / graphics processor is the default processor to handle video
> scaling. Hence no option in the Nvidia control panel.
>
>
> In the nvidia control panel you should only have 3D and video options.
> The "display" options for which the scaling is located in the nvidia
> control panel is not needed since the intel driver handles that part.
>
>
> So yeah, in a nutshell there's no problem.
>
>
>
Another entry in the same thread says :
>
> Not having experience with Optimus it was just a guess, as it works
> that way on my PC with HD4000 and AMD gpu.
>
>
> When the integrated is selected as default in BIOS the AMD control
> panel is not fully functional (Don't have integrated on the Nvidia
> machine). I find it more difficult to get good results with the HD4000
> re - aspect ratio.
>
>
>
If your BIOS has an option to define the nVidia Geforce as default,
this might fix the problem, but might place more demand on your battery.
---
The thread [Stereoscopic 3D missing in nvidia control panel](http://roadzy.blogspot.fr/2013/10/stereoscopic-3d-missing-in-nvidia.html) has a simpler solution,
which is to ensure during the Nvidia driver installation that all its components
are marked for installation, even the ones that are unchecked by default since
they are currently handled by the on-board Intel adapter.
Try to reinstall the Nvidia driver to see if this is also true in your case.
You could also go on the [NVIDIA Driver Downloads](http://www.nvidia.fr/Download/index.aspx?lang=en-us) page and use the automatic detection
mechanism via the "GRAPHICS DRIVERS" button, to see if it suggests the same driver
package that you have already downloaded.
This requires Internet Explorer or having Java installed for other browsers. | This sometimes happens to me, I have to go into Device Manager and disable/enable one of the card for the control panel to update.
As a side note when it's happening the start bar spans across all my monitors (normally with spanning it is only on the primary screen)
Hope this helps. |
136,570 | I am currently a mobile developer and have been that for about 7 years now and I have been in IT for about 10. So I'm an experienced IT professional. I'm considering changing careers to either cyber security or computer forensics. But I would have to take an entry level position for cyber security or computer forensics. If I am at 95,000 a year as a developer would I be able to ask for the same or would I have to accept whatever the entry level pay is for one of those 2 careers? | 2019/05/14 | [
"https://workplace.stackexchange.com/questions/136570",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/104688/"
] | You should expect your pay to be based on how well your skills and experiences fit the requirements for the new position.
Specifically, you asked,
>
> If I am at 95,000 a year as a developer would I be able to ask for the same or would I have to accept whatever the entry level pay is for one of those 2 careers?
>
>
>
**What you made as a developer is essentially irrelevant.** The thing that matters is, what is a typical salary for an employee in the position you're seeking? If your skills in security match what an "entry level" person typically needs, and an entry level security tech makes 50k (or 100k, or whatever the number is), then **that's what you should expect to make.**
As with any career path change, be sure to prepare for inevitable questions in interviews - why are you making the change? What research have you done about the new role? What have you done to prepare yourself? How will your old skills help you in the new role?
In addition to proving that you're a good fit for the new role, you should also be ready to show that this is a carefully considered and prepared-for change, and not something you're doing on a whim. Employers are leery of career-path-switchers who act like they may be a risk for continual change - you don't want to come across as someone who's going to try out the new role and then jump back to your old stuff after 6 months, or leave for something else totally new. | There is no right answer to this question I'm afraid.
To give you an example, I moved from Application Support into Project Management and received a substantial pay increase instead.
If the company you apply for to work in cyber security is mainly a mobile development company, they may pay you more since you not only know how to secure their product but understand how it was built, which helps you know better how to break some of the features, so you have an advantage over other people.
If instead you apply for a company with no mobile presence in a completely different market you have worked in, then the only benefit to the company is your cyber security knowledge, which as you have pointed out, might be lower than other candidates that have been working in the field for a while.
Be prepared to negotiate, but most importantly, if it is what you REALLY want to do, job satisfaction is more important than your salary (if you can afford the cut) |
37,923,139 | I want to make view or simply to get some data from database but in specific way.
For example if data is :
```
1 | test | test | 0 | test
2 | test | test | 1 | test
3 | test | test | 1 | test
4 | test | test | 1 | test
5 | test | test | 0 | test
```
The output should be:
```
1 | test | test | FALSE | test
2 | test | test | TRUE | test
3 | test | test | TRUE | test
4 | test | test | TRUE | test
5 | test | test | FALSE | test
```
Any ideas? | 2016/06/20 | [
"https://Stackoverflow.com/questions/37923139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6330830/"
] | Use [**`CASE`**](https://msdn.microsoft.com/en-us/library/ms181765.aspx?f=255&MSPPError=-2147217396) expression.
**Query**
```
SELECT col1, col2, col3,
CASE col4 WHEN 0 THEN 'False'
WHEN 1 THEN 'TRUE'
ELSE NULL END AS col4, col5
FROM your_table_name;
``` | An `if` condition in SQL is expressed using [`CASE` expression](https://msdn.microsoft.com/en-us/library/ms181765.aspx?f=255&MSPPError=-2147217396):
```
SELECT
id
, a
, b
, CASE c WHEN 0 THEN 'FALSE' ELSE 'TRUE' END AS c
, d
FROM my_table
```
Note that there are two forms of `CASE` expression in SQL Server - simple and searched. The above is an example of a simple. |
22,256,267 | I'm just trying to get this program to take a number between 1 and 9 and calculate the radius and display it. This program is supposed to loop but all I'm getting is the "Thank you for using the software!" print function, it's not going through the loop at all and I can't seem to understand why.
```
#include <stdio.h>
int main(void){
float i,r, V;
for(i=0; i <= 4; i++){
while ( r != 0) {
printf("Enter a radius between 1 and 9: \n");
scanf ("%f", &r);
V= (3.141592)*r*r*10;
if (r>=1 && r<=9){
printf("The cylinder volume is %f\n", V);
}
else if (r > 9 || r < 0){
printf ("The input is out of the acceptable range. Select an integer less than $/n");
}
printf("Thank you for using the software!\n");
}
return 0;
}
``` | 2014/03/07 | [
"https://Stackoverflow.com/questions/22256267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3258789/"
] | You never *initialize* `r` before entering your `while` loop, so this is undefined behavior.
Additionally, you want to use `int` s for equality operators, i.e. `==` or `!=`. In your case, you might want to include an "error" that `r` can be within. | you have not initialize r before using it.
you must initialize it or use i to iterate though the loop.
```
INITIALIZE r here before using
for (i = 0; i <= 4; i++)
{
while (r != 0)
{
//code
}
}
``` |
31,339,762 | I've looked all over the web for this, and nothing I found seems to help.
I made a model and added the model to a data source as an object. I assumed it would work like a data set where I can just drag and drop onto a form and it would bind the data for me. But it keeps showing blank when I drag and drop from the model. so I looked online and saw that some code-behind was required and this is what I have and its still blank. Any ideas what Im doing wrong?
```
public partial class form1: Window
{
ComEntities context;;
public form1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
context = new ComEntities();
System.Windows.Data.CollectionViewSource comEntitiesViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("comEntitiesViewSource")));
var permits = (from c in context.tBLPER.Local select c);
this.DataContext = context.tBLPER.Local;
tBLPERDataGrid.ItemsSource = context.tBLPER.Local;
}
}
```
XAML:
```
<DataGrid x:Name="tBLPERDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Margin="10,10,10,413" ItemsSource="{Binding}" EnableRowVirtualization="True" AutoGenerateColumns="False">
</DataGrid>
``` | 2015/07/10 | [
"https://Stackoverflow.com/questions/31339762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5094751/"
] | You need to materialize your query (bring the data to memory). You can do that calling the `ToList()` method, but even better is do this:
```
context.TBLPER.Load();
this.DataContext = context.TBLPER.Local; // set the Window DataContext property
```
`Local` property gets an `ObservableCollection<T>` that represents a local view of all `Added`, `Unchanged`, and `Modified` entities in this set. This local view will stay in sync as entities are added or removed from the context. Likewise, entities added to or removed from the local view will automatically be added to or removed from the context.
In case you need to filter your data before (suppose your entity has a property named `Age` and want the users older than 20), then you can do this:
```
context.TBLPER.Where(t=>t.Age>20).Load();
this.DataContext = context.TBLPER.Local;
```
Another thing, if you want to set the `ItemSource` property of your Grid in the code behind of your window, it don't make sense create a binding to that property in your xaml code, so remove it:
```
<DataGrid ... ItemsSource="{Binding}" ...>
```
If you are going to do this:
```
tBLPERDataGrid.ItemsSource=context.TBLPER.Local;
``` | You shouldn't be setting `ItemsSource` twice (just set it in your code behind - remove `ItemsSource="{Binding}"`).
Also, you should set `AutoGenerateColumns="True"` because without that you need to add `DataGrid`X`Column` elements to the `DataGrid`.
Have a look here for more details ... <http://www.wpf-tutorial.com/datagrid-control/custom-columns/>
You may also want to put a breakpoint on the `tBLPERDataGrid.ItemsSource = permits;` line so you can inspect `permits` to confirm it contains the data you expect. |
528,707 | I'm looking for an editor that has the help from
<http://www.hibernate.org/hib_docs/nhibernate/html/mapping.html>
built in, and allows simple editing of the XML files in a GUI fashion. I realise there's CodeSmith and MyGeneration, but from what I remember these only go one way, and don't allow editing existing HBM files. | 2009/02/09 | [
"https://Stackoverflow.com/questions/528707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21574/"
] | Have you tried Hibernate's own Eclipse plug-in named *Hibernate Tools for Eclipse and Ant*?
<http://www.hibernate.org/255.html>
Even if you dont have expirience with Eclipse and its add-ons it should be fairly straightforward to install and use their addon:
Just download it, unzip it into the eclipse directory, and fire up the IDE.
What you need to do next is to open up the Hibernate perspective. | I'm using VisualStudio and the schema (nhibernate-mapping.xsd) to activate the intellisense.
The plug-in for R# is useful to check the mapping with the class. |
905,729 | I'm building up a new machine with a Supermicro MB equipped with a TPM and a Seagate Constellation ES.3 SED drive (ST200NM0053). The MB has the AMI BIOS which does see the TPM.
I've installed Windows Server 2012 R2 Essentials. I'm now struggling to enable hard drive encryption using the SED feature of the hard drive.
My understanding (which is pretty weak) is the Windows BitLocker software can work with the TPM to support hard drive encryption but that Windows requires the hard drive to support OPAL 2, which the Seagate drive does not support.
I don't think I need to be concerned about this, because I'm under the impression that with this Seagate drive and a MB that supports TPM, I can enable the encryption regardless of what OS is running and manage the encryption, its related keys, backup, migration, etc. all through the BIOS. Furthermore, the OS won't even see that the drive is encrypted and needs no encryption capabilities or support at all.
But how do I enable encryption through the BIOS? I've gotten as far as enabling the TPM but I don't see anywhere where I can encrypt the drive or change the default password that the manufacturer installed on the drive.
What are my next steps and where might they be documented? | 2015/04/24 | [
"https://superuser.com/questions/905729",
"https://superuser.com",
"https://superuser.com/users/359463/"
] | Writing to SSDs isn't necessarily bad. It's the writing and rewriting of a single block that's bad. Meaning if you write a file delete it then write it again, or make small amounts of changes to a file over and over again. This causes wear on the SSD's. Databases would definitely fit into this category.
However according to [this article](http://www.zdnet.com/article/worried-about-ssd-wear-you-probably-dont-need-to-be/), petabytes of data have been written to SSDs and still been operable. This is probably due to advances to [wear leveling](http://en.m.wikipedia.org/wiki/Wear_leveling):
>
> Wear leveling attempts to work around these limitations by arranging data so that erasures and re-writes are distributed evenly across the medium. In this way, no single erase block prematurely fails due to a high concentration of write cycles.
>
>
>
In your particular situation I would have the databases reside on the SSD for speed, but backed up on a daily basis. You also might consider getting two SSDs in a [RAID 1](https://en.wikipedia.org/wiki/RAID#Standard_levels) array as well. The likelihood of two SSDs failing at the same time is low.
Note: RAID arrays are NOT backups!!!! No matter if you use a RAID array or not, have a backup. No matter if you use an SSD or not, have a backup. | If you are truly interested in figuring out the details then you will need the following question answered:
**On average how many bytes are in each row?**
If you can tell me that there are 10 columns, each column is varchar(100), and the encoding is UTF-8 then I can guess at worst case scenario that you have 4,000 bytes worth of data per row and add some more bytes for meta-data so lets say 4,200 bytes?
Your torture SQL calculates to `4,200 x 100 x 100,000,000 = 42,000,000,000,000 bytes` of data written to the disk
>
> 42,000,000,000,000 / 1000 = 42,000,000,000 KB
>
>
> 42,000,000,000 / 1000 = 42,000,000 MB
>
>
> 42,000,000 / 1000 = 42,000 GB
>
>
> 42,000 / 1000 = 42 TB
>
>
>
At this theoretical worst-case scenario you will be writing 42 TB to the disk
According to this **[article](http://www.zdnet.com/article/worried-about-ssd-wear-you-probably-dont-need-to-be/)**, provided by @KronoS you should be good for about 25 more rounds of your torture SQL. |
52,233,250 | I have a list and I want to apply border bottom to it, here is what I want
[](https://i.stack.imgur.com/9rn3O.png)
here is what I have so far.
[](https://i.stack.imgur.com/qj4wE.png)
here is jsfiddle: <https://jsfiddle.net/Mwanitete/vr1c8tgo/10/>
```css
.data-right-bottom ul li {
margin: 10px;
list-style-type: none;
display: flex;
width: 400px;
border-bottom: 1px solid green;
}
.data-right-bottom ul li span {
flex: 1 0 0;
width: 400px;
}
```
```html
<div class="data-right-bottom">
<ul>
<li style="display: none;">
<span>Total wrapping (tax incl.)</span>
<span id="total_wrapping_right" class="total_wrapping_right">0,00 zł</span>
</li>
<li>
<span>Total products (tax incl.)</span>
<span id="total_product_right" class="total_product_wt_right">210,00 zł</span>
</li>
<li>
<span>Total shipping (tax incl.)</span>
<span class="total_shipping_right">
12,00 zł
</span>
</li>
<li class="order-subtotal">
<span>Total (tax excl.)</span>
<span class="total_price_without_tax_right">182,73 zł</span>
</li>
<li class="order-discounts" style="display:none">
<span>Total discounts</span>
<span class="total_discount_right">0,00 zł</span>
</li>
<li class="order-tax">
<span>Total tax</span>
<span class="total_tax_right">39,27 zł</span>
</li>
<li class="order-total">
<span>Total</span>
<span class="total_price_right">222,00 zł</span>
</li>
</ul>
</div>
```
what am i missing here? any help will be apreciated | 2018/09/08 | [
"https://Stackoverflow.com/questions/52233250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9964622/"
] | Another option besides Lazar Nikolic's one is to use a CSS table instead of a flexbox. After all, that's what it is; it displays tabular data.
To make it responsive as you wanted, you can always use a media query to turn it back into a series of blocks so that everything is displayed underneath each other.
```css
.data-right-bottom ul {
display: table;
}
.data-right-bottom ul li {
list-style-type: none;
display: table-row;
}
.data-right-bottom ul li span {
display: table-cell;
border-top: 1px solid green;
}
.data-right-bottom ul li span:last-child {
padding-left: 10px;
text-align: right;
}
@media all and (max-width: 17em) {
.data-right-bottom ul li {
display: block;
border-top: 1px solid green;
}
.data-right-bottom ul li span {
display: block;
border-top: none;
}
}
```
```html
<div class="data-right-bottom">
<ul>
<li style="display: none;">
<span>Total wrapping (tax incl.)</span>
<span id="total_wrapping_right" class="total_wrapping_right">0,00 zł</span>
</li>
<li>
<span>Total products (tax incl.)</span>
<span id="total_product_right" class="total_product_wt_right">210,00 zł</span>
</li>
<li>
<span>Total shipping (tax incl.)</span>
<span class="total_shipping_right">
12,00 zł
</span>
</li>
<li class="order-subtotal">
<span>Total (tax excl.)</span>
<span class="total_price_without_tax_right">182,73 zł</span>
</li>
<li class="order-discounts" style="display:none">
<span>Total discounts</span>
<span class="total_discount_right">0,00 zł</span>
</li>
<li class="order-tax">
<span>Total tax</span>
<span class="total_tax_right">39,27 zł</span>
</li>
<li class="order-total">
<span>Total</span>
<span class="total_price_right">222,00 zł</span>
</li>
</ul>
</div>
``` | Maybe you should change the width of your span to 200px (Span are two inside a "li"). |
38,993,733 | So essentially I have two matrices:
```
A<-matrix(runif(10*10),ncol = 10)
B<-matrix(runif(10*10),ncol = 10)
```
I am trying to create a for loop which will:
a)remove the top row of matrix A and and add the top row of matrix B to the bottom of the new matrix A, to create a matrix a.
b)remove the 2 top rows of matrix A and and add the 2 top rows of matrix B to the bottom of the new matrix A,to create a matrix b
c)remove the 3 top rows of matrix A and and add the 3 top rows of matrix B to the bottom of the new matrix A, to create a matrix c
. . .
I could write this manually like the code below shows, but I need to do this for a bigger matrix so it will take me much longer:
```
a<-rbind(A[2:10,],B[1:1,])
b<-rbind(A[3:10,],B[1:2,])
c<-rbind(A[4:10,],B[1:3,])
d<-rbind(A[5:10,],B[1:4,])
.
.
.
```
Here is my attempt at creating the for loop:
```
A<-matrix(c(rep(0,10*10)),nrow=10)
n<-10
for (i in 1:n-1){
A<-rbind(R[(i+1):10,],ER[(1:i),])
}
```
This only outputs the n-1 matrix, but I would like all my matrices to be output. | 2016/08/17 | [
"https://Stackoverflow.com/questions/38993733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6725750/"
] | One idea is to create a function that takes as arguments the matrices and the rows. Then use `lapply` to iterate,
```
fun1 <- function(x, y, n) { rbind(x[n:nrow(x),], y[1:n-1,])}
lapply(2:nrow(A), function(i) fun1(A, B, i))
``` | I made a few change to your solution, and I used the variable `letters` which provide a list, for instance `letters[2]=b`.
To assign each new matrix to a dynamic variable, I used the function `assign`.
```
A<-matrix(runif(10*10),ncol = 10)
B<-matrix(runif(10*10),ncol = 10)
n<-nrow(A)
for (i in 1:(n-1)){
assign(letters[i],rbind(A[(i+1):10,],B[(1:i),]))
paste(letters[i])
}
``` |
352,931 | I'm making the transformation from being a web developer whose pages often contain loads of `<script>` tags to one whose pages contain modular Javascript, encapsulated in functions, etc. I'm trying to work out the best way to handle the situation where the code in a particular script file assumes that another script has already been loaded.
For example, my markup may look like this at the moment...
```
<script src="SomeCommonUtil.js"></script>
<script src="PageSpecificScript.js"></script>
```
...where the code in `PageSpecificScript.js` assumes that the code in `SomeCommonUtil.js` has already been loaded.
I would like to improve this, but am not sure the best way to go about it.
Looking around, it seems that [requires.js](http://requirejs.org/) is a popular approach, but then I see things like [require.js](http://requirejsnet.veritech.io/) and others as well. I'm struggling to work my way through this, and was hoping someone could give me some guidance.
We develop ASP.NET MVC5 web sites, and use the [KendoUI library](http://www.telerik.com/kendo-ui) for widgets. We've just started using KendoUI's MVVM framework as well.
Any guidance would be appreciated. | 2017/07/17 | [
"https://softwareengineering.stackexchange.com/questions/352931",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/123358/"
] | Based on the clarification, you might be talking about JavaScript package management. The two big ones I know about are Node Package Manager (NPM) and Bower. VisualStudio has Bower integration, so that might be a good match for you.
The JavaScript package managers keep track of the dependencies between your dependencies, so that when you include something like KendoUI, then the package manager will download and integrate all the dependencies it needs.
---
What many websites do these days is create a consolidated and minimized version of the JavaScript. There are a few ways to go about doing this, depending on how you want to manage it.
Asp.Net MVC 5 has the concept of creating [resource bundles](https://docs.microsoft.com/en-us/aspnet/mvc/overview/performance/bundling-and-minification) which reduces the number of resources the browser has to pull down, and the size of the resource. I'm not aware to what extent that MVC goes through to remove code that is never called, but this process works pretty well.
Some specific JavaScript tools (like Sencha ExtJS) have a proprietary tool to handle the bundling and minification for you. Typically, it will remove parts of the library you are not using, and it doesn't break the library when minifying the code.
A pure JavaScript solution is to use something like [WebPack](https://github.com/webpack/webpack) to generate both the bundled JavaScript, and a map file for debugging. The map file is a standard understood by Firefox and Chrome (with more browsers coming on line) that lets you run the minimized code, but interact with the JavaScript in your browser's debug window as if it were separate files. WebPack has the added bonus of being able to transpile JavaScript 6 code down to JavaScript 5 for those legacy browsers (like Internet Explorer).
Having used all three solutions I'm aware of some tradeoffs:
* Resource Bundles are easy to set up and integrate. They just lack the mapping file to make debugging easy.
* Proprietary libraries that have proprietary bundling tools really need them. We've had our JavaScript break in unpredictable ways on different browsers when using resource bundles.
* Webpack has a high learning curve, but is capable of doing some very impressive things. If you intend on using React, it's almost a necessity. If you have a UI that is talking to a REST API layer, it's the way to go.
The short answer is, you are probably going to get the most bang for your buck by using resource bundles in your particular case. | If you don't want to go through the effort of setting up an AMD loader like require.js, MVC 5 comes with a built in way to handle things like this with its BundleCollection library. A new MVC project should automatically setup this up for you in the BundleConfig.cs class in App\_Start and give a very basic example of its use.
You can combine one or more javascript files into a bundle, which you reference in the HTML instead of the script tags. These scripts are automatically combined into one script and minified when published in Release mode (or setting <compilation debug="false" /> in the Web.Config). In development the script tags are just written to the HTML.
Microsoft has a decent tutorial on this here: <https://docs.microsoft.com/en-us/aspnet/mvc/overview/performance/bundling-and-minification>
You can bundle css files too, but one thing to watch out for is that relative paths in the css files to images can easily be broken.
To fix this, do the following:
```
bundles.Add(new StyleBundle("~/cssbundles/bootstrap").Include("~/Content/bootstrap.css", new CssRewriteUrlTransform()));
```
This changes the relative paths in the .css file to absolute paths.
Depending on the complexity of your javascript dependencies and what kind of application you're writing (SPA or not), this may be an easier solution. If you just want to always load a bunch of javascript files when using at least one if them, it's easy to setup and use and reduces the load on the client by bundling/minifying. |
21,258,723 | I discovered by accident that an assignment operator returning not a reference, but a copy, serves as a workaround to enable storing objects with `const` members in an STL container.
```
class Test_class
{
public:
int const whatever;
explicit Test_class(int w) : whatever(w) {}
// note the missing &
Test_class operator=(Test_class const& rhs) {
return Test_class(rhs.whatever);
}
};
vector<Test_class> vec;
Test_class foo(42);
vec.push_back(foo);
assert(vec[0].whatever == 42);
```
This piece of code *feels* very strange, but gcc compiles it and it seems to work correctly.
So where are the pitfalls?
**EDIT:**
After the `push_back()` `vec[0].whatever` is, in fact, 42. Added an assert for illustration.
**EDIT:**
Thanks for the answers! Just for the fun of it, this version also runs just fine ;)
```
void operator=(Test_class const&) {
throw 42;
}
``` | 2014/01/21 | [
"https://Stackoverflow.com/questions/21258723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/621053/"
] | Most of the accepted practice for operator overloading is not enforced by the standard or the compiler. It's just an expectation on the behaviour. You can check out some of it here: [Operator overloading](https://stackoverflow.com/questions/4421706/operator-overloading) or here: <http://en.cppreference.com/w/cpp/language/operators> .
The pitfall here is that your `operator=` is not really an assignment operator. Consider this code:
```
Test_class a(15);
Test_class b(20);
a = b;
```
Normally you would expect `a.whatever` to be 20 after executing this code, however it's still 15.
C++03 requires vector elements to be both copy-constructible and copy-assignable and the compiler is free to choose what to use. In C++11 they only have to be copy-constructible (or move-constructible) so no assignment operator is required. | You don't actually assign anything here. You could even declare that assignment operator as `const` because it does nothing.
```
Test_class a(17);
Test_class b(33);
a = b; // nothing happens.
```
The return value of operator= doesn't really matter, I for one typically declare it as `void`. It only matters if you do things like `a = b = c;`, which is not very common. And with your `operator=` this will compile, but again, does nothing at all. |
22,129,676 | The following code produces nothing on the html page, it seems to break down on 'status':
```
var get_json_file = new XMLHttpRequest();
get_json_file.open("GET", "/Users/files/Documents/time.json", true);
**document.write(get_json_file.status);**
```
keep in mind, that I am on a Mac, so there is no C: drive....however, this line of code does work fine:
```
document.write(get_json_file.readyState);
```
I just want to know that I was able to successfully find my json file. Perhaps, I should ask, what should I be looking for to achieve what I want ? | 2014/03/02 | [
"https://Stackoverflow.com/questions/22129676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3134565/"
] | Another basic question about AJAX. I suggest you to read the [MDN article](https://developer.mozilla.org/es/docs/XMLHttpRequest) about using XMLHttpRequest. You can't access the 'status' property until it is ready, and you haven't even called the 'send()' method, which performs the actual request. You can't have a status without making an HTTP request first. Learn how AJAX works before trying to use it. Explaining it all would be too long and this is not the place. | You can only get the status when the ajax has finished. That is, when the page was loaded, or a 404 was returned.
Because you're trying to call `status` straight after the request was sent *(or not sent, read the P.S)*, you're getting nothing.
You need to make an async call, to check that status only when the request finishes:
```
get_json_file.onreadystatechange = function (){
if (get_json_file.readyState==4 && get_json_file.status==200)
{
alert('success');
}
}
```
read more at <http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp>
**P.S** as noted by @Oscar, you're missing the `send()`.
---
If you want to try a synchronous approach, which would stop the code from running until a response is returned, you can try:
```
var get_json_file = new XMLHttpRequest();
get_json_file.open("GET", "/Users/files/Documents/time.json", false);
//notice we set async to false (developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)
get_json_file.send(); //will wait for a response
document.write(get_json_file.status);
//(Credit: orginial asker)
``` |
62,678,888 | This is my login.jsp file.
```
<form:form method="POST" action="checklogin" modelAttribute="log">
<form:label path="username">UserName: </form:label>
<form:input path="username" id="username" /><br /><br />
<br />
<form:label path="pswd">Password: </form:label>
<form:password path="pswd" id="password" /><br /> <br />
<br />
<input type="submit" id="btnLogin" value=login class="login" />
</form:form>
```
This is my controller
```
@RequestMapping(value = "/checklogin", method=RequestMethod.POST)
public String chklogin(@ModelAttribute Login login, Model mod) {
if (login.getUsername().equals("subro") && login.getpswd().equals("ss")) {
mod.addAttribute("log",login);
return "Home";
}
else {
return "Login";
}
}
```
Still I am getting the error as
Neither BindingResult nor plain target object for bean name 'log' available as request attribute | 2020/07/01 | [
"https://Stackoverflow.com/questions/62678888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13847690/"
] | Change
```
@ModelAttribute Login login
```
To
```
@ModelAttribute Login log
``` | Two way data binding in spring allows user inputs to be dynamically bound to the beans. It is two-way in a sense that it can get the inputs from the beans and it can post the user inputs to the beans using GET and POST api.
Using the `@ModelAttribute` annotation you can bind the user inputs with the beans.
```
@RequestMapping(value = "/login", method=RequestMethod.GET)
public String login(@ModelAttribute Login log){ //one-way binding
return "Login";
}
@RequestMapping(value = "/checklogin", method=RequestMethod.POST)
public String chklogin(@ModelAttribute Login log, Model mod) { //two-way binding
if (login.getUsername().equals("subro") && login.getpswd().equals("ss")) {
mod.addAttribute("log",login);
return "Home";
}
else return "Error";
}
```
Earlier I haven't written the login method which is mapped with the url `/login`.
When you are getting an error as "Neither BindingResult nor plain target object for bean name 'log' available as request attribute", it means that the beans ('log' in my case) is not able to bind with the view page. |
41,877,856 | Suppose i have four pages and two user types. After logged in, user one can access all the four pages but for second user we are restricting to access only 2 pages. How can we achieve this in angular 2..? | 2017/01/26 | [
"https://Stackoverflow.com/questions/41877856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5527668/"
] | You can create a guard. Let's take this example:
```
import {Injectable} from '@angular/core';
import {CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {UserService} from '../auth';
@Injectable()
export class RoleGuard implements CanActivate {
constructor(private userService:UserService, private router:Router) {
}
canActivate(next:ActivatedRouteSnapshot, state:RouterStateSnapshot) {
if (this.userService.hasRole('ROLE_ADMIN')) {
return true;
}
this.router.navigate(['some-other-route']);
return false;
}
}
```
Then you add it to your routing:
```
path: 'pathToAdminRoute',
component: SomeComponent,
canActivate: [RoleGuard]
```
What it does is make that particular route only accessible by a user with a specific role (in this case - a user with a role of `"ROLE_ADMIN"`) | You can use Angular2 `guards` (*viz.* `CanActivate`, `CanActivateChild`, `CanDeactivate` & `CanLoad`) to protect/control access to various routes (pages).
For a better understanding, please read this - [PROTECTING ROUTES USING GUARDS IN ANGULAR](https://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html) |
1,998,426 | I don't think a similar question has been asked yet, but I've been stumped by the following problem and was hoping maybe someone could spare a few moments to help me out.
$\lim\_{x\to\:3}\left(\frac{5x^2-8x-13}{x^2-5}\right)ln\left(\frac{4x+2}{4x+5}\right)$
I can't use l'hopital to solve this problem and even online limit calculators can't seem to handle this one quite well.
I am very grateful for your help!
Best Regards
Dave | 2016/11/04 | [
"https://math.stackexchange.com/questions/1998426",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/385818/"
] | >
> On the one hand this passage should be valid because it is just the definition of logaritm
>
>
>
No, it is *not* valid in general, since $x^n = e^{n \ln x}$ is *only* valid for $x \gt 0$.
One could technically use $x = |x| \cdot \operatorname{sgn}(x)$ to write it as $$x^n = e^{n \ln |x|} \cdot \operatorname{sgn}(x)^n \quad \forall \;x \in \mathbb{R} \setminus \{0\}, \;n \in \mathbb{Z} $$
though that would look quite odd in practice. Most often, one would use an appropriate substitution to first remap the variable to a positive domain, instead. | Of course if you use $e^{x\ln a}$ instead of $a^x$ then $a>0$ because otherwise the exponent $\ln a$ is not real any more.
(1) It's $e^{x\ln a}=a^x$ for $a>0$ ;
(2) it's only $a^x$ (and not $e^{x\ln a}$) valid for $a\in\mathbb{R}\setminus\{0\}$ with $x\in\mathbb{Z}$.
$e^{x\ln a}$ and $a^x$ are two different kind of constructions for evaluations and the value ranges have to be considered. |
195,775 | I have a piece of paper whose shape is a regular `n`-gon with side length `1`. Then I fold it through some of its diagonals. What is the area of the shape formed by the (former) edges of the regular polygon?
Illustration
------------
Suppose `n = 8`, i.e. an octagon-shaped paper. Let's name the vertices from A to H (left picture). Then I fold the paper along the two diagonals BE and FH (right picture). Mathematically, folding BE means to reflect the vertices C and D with respect to the line BE to obtain C' and D'. Your task is to calculate the area of the shaded octagon on the right picture.

Input
-----
The number of sides `n` and a list representation of the folds `l`. Each element of `l` represents either a fold or an intact side of the polygon. If it is a fold, its value is the number of sides moved by the fold (e.g. 3 for the `BE` fold above, 2 for `FH`). Otherwise, the value is 1 (e.g. for the sides `AB`, `EF`, `AH`).
For the example above, the input will be `8, [1, 3, 1, 2, 1]` if we count from the vertex A, counter-clockwise. If we count clockwise from E instead, the input will be `8, [3, 1, 1, 2, 1]`; the expected answer is the same.
Note that `sum(l) == n`. Also, `l == [1] * n` (1 repeated n times) case is just the regular polygon untouched, which is a valid input.
**The resulting polygon is guaranteed to be simple** (it does not intersect or touch itself). For `n=3` or `n=4`, this means that the only valid input is the polygon folded zero times. For `n=6`, `l=[1, 2, 2, 1]` or `l=[1, 2, 1, 2]` is invalid because the two folds will cause two folded vertices to meet at the center of the hexagon.
Output
------
The area of the `n`-sided polygon created by the given folds. The result must be within `1e-6` absolute/relative error from the expected result.
Scoring & winning criterion
---------------------------
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. Shortest code in bytes wins.
Test cases
----------
```
n l => answer
---------------
4 [1, 1, 1, 1] => 1.000000
5 [1, 1, 1, 1, 1] => 1.720477
5 [2, 1, 1, 1] => 0.769421
6 [1, 2, 1, 1, 1] => 1.732051
7 [1, 2, 1, 2, 1] => 2.070249
8 [1, 3, 1, 2, 1] => 1.707107
```
The picture below shows the first five test cases.

[A reference implementation in Python](https://tio.run/##XZHBaoQwEIbvPsXAHjYR17aubouwpz5G6SHoRAOaSMxSltJnt5OktlqIMn4zf/6Zcbq73ujzshzgVQzNbRAOwfUIwqIAI0NssaOEhckM985o@FCuh1m1CAPqjuKnLLIGrRNKB/EM0gwttom0ZoRRUFqNk7EuhQOJdQaNmTOYVAZ5nictSpDMX0rQK2deJ@DtnYArlcFDsJwJWgKPeRWIZqGEE@5/sRMbPClskFI9JQryXqeIPHTXoHZofS3lgptPpdGQJDcdZ1m1VCmNBQU0a@jVt/qjPl2BrXoFp9BRSi3HxzdchEwaZ@OcosJbW6XdbgEZHD/r/CK/jjm50QaZN@A87KqLpbzeCmlCVvqbaf6/jXHOF8nKDN7oP9Ep3nmy/fYnoGqHtrTYo0ss/Eeft7RY6Uuk5y3tWOlfFV@@AQ). | 2019/11/13 | [
"https://codegolf.stackexchange.com/questions/195775",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/78410/"
] | Java 8, ~~123~~ ~~114~~ ~~112~~ 103 bytes
=========================================
```java
a->n->{double t=Math.PI/n,T=Math.sin(t);n/=-Math.tan(t);for(int v:a)n+=Math.sin(2*v*t)/T/T;return n/4;}
```
Port of the Python reference implementation.
-11 bytes by porting [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/195777/52210).
-9 bytes thanks to [*@G.B*'s insight](https://codegolf.stackexchange.com/questions/195775/area-of-diagonal-folded-regular-polygon/195792?noredirect=1#comment465934_195777).
[Try it online.](https://tio.run/##hZJLb8IwDIDv/AqrpwbaVBTYJjqQJk1IOyBNgxvikNEUwkpaNW4nhPjtLKQwXt1oDo3tz3b8WLKCucvwazeLmVIwZEJuagAKGYoZLLWV5ihiGuVyhiKRdHC4PAuJk6nzL/Ka5J8xd6D89/sQQW/H3L50@5vQ6AB7Q4YL@v7mSWdc3pWQNpJAej3XyMiMHCWZrXNC0WVENk6oXy/qSLyxNw4yjnkmQXrtYLsLarqOVCfRdRzKKRIRwkqXaI8wE3I@mQIj@3IBRmuFfEWTHGmqTRhL2xqJkKuu1bDAohlPOUO7QxrWIInDK7W/139wlcfYBYuY1ADIFdotByT/BtOtTdPRZ6vtv@b2jfke4F@YOxX@VxEuEL8CeLiMUYU83iL@FfJ0ibTOkW3ttFNmCMbjsAJq32andIRo39y/Z2LY8843m@5RaREacznHhU1I47SWL1nG1opiUs7cLjOcx2g13Xv4WWTztIovoixN4/XRoRTM08ihB9vdDw) | [R](https://www.r-project.org/), ~~60~~ 57 bytes
================================================
-2 and -1 thanks to Nick Kennedy and CriminallyVulgar!
```r
function(n,l,t=pi/n)(sum(sin(2*t*l)/sin(t)^2)-n/tan(t))/4
```
[Try it online!](https://tio.run/##TcrNCoAgEATge0/RcVcMyX4P9SpBBIJgW9T6/EbSj8xl5mOOYPKhCMbTwnYjIOkkj7tVhHD6FU5LoAULh@qujJPGghTPd0dVBwO1XKCUMYiZgebfiehkt/GRSveJfqSPUr0SLg "R – Try It Online") |
6,992,139 | I have a UITableViewController. When a certain BOOL is set, I want to show another view instead of the UITableView. How can I do this? I need to be able to bring the UITableView back also. | 2011/08/09 | [
"https://Stackoverflow.com/questions/6992139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19875/"
] | I implemented the following method in my Table view controller subclass to reload its background.
```
- (void)reloadBackground
{
if(myBool)
{
//load the view to be displayed from a nib
NSArray* nibs = [[NSBundle mainBundle] loadNibNamed:@"EmptyView" owner:self options:nil];
UIView* emptyView = [nibs objectAtIndex:0];
self.tableView.backgroundView = emptyView;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
else
{
self.tableView.backgroundView = nil;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
}
}
```
HTH,
Akshay | Possibly something like:
```
if (myBool == YES) {
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
[self.view addSubview:myView];
}
```
Now to get rid of it:
```
[myView removeFromSuperview];
```
Of course there are plenty of other methods...
Even: `self.view = myView;` |
15,433,734 | The question has surely already be asked, but I didn't find it.
I am often forced to write code like that in views:
* `<div class="<%= c ? 'my_class' : 'my_other_class' %>">`
* `<div class="<%= 'my class' if c %>">`
* `<div<%= c ? 'class="my_class"' : 'id="my_div"' %>>`
Or (the prettier way, but the less readable) :
```
<% div_inner = capture do %>
...
<% end %>
<% if c %>
<div class="my_class"><%= div_inner %></div>
<% else %>
<div><%= div_inner %></div>
<% end %>
```
A last one :
```
<% div_inner = capture do %>
...
<% end %>
<%= content_tag(:div, div_inner, (c ? { :class => "my_class" } : {})) %>
```
I found all this solutions syntactically dirty. I am convinced that there is a nicer way. But witch ?
Your own experiences are welcome. | 2013/03/15 | [
"https://Stackoverflow.com/questions/15433734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1611683/"
] | You're correct in assuming there is a nicer way. Putting conditional logic into views is against the spirit of MVC. Based on your examples you would be fine to use a simple helper method rather than any of the more complicated implementations that you might read about around the web.
You could create a helper method that looks something like this
```
def conditional_div(condition, true_class, false_class)
content_tag :div, class: (condition ? true_class : false_class) do
yield if block_given?
end
end
```
Then in your view you can use the new helper like this
```
<%= conditional_div(c, 'my_class', '') do %>
<p>Your content</p>
<% end %>
``` | Depending on what you're doing, if the condition `c` is somewhat "global" (like the current page's name, or language, or whether the user is currently logged in, or whether it's morning or evening.... ), it can make sense to set these as the `body` element's CSS classes so the output looks like this:
```
<body class="is_home_page lang_en is_logged_in">
```
and to do the rest in CSS:
```
body.is_home_page .classname { color: red }
body.is_sub_page .classname { color: green }
```
that can will the overall HTML easier to read. |
30,056,024 | I have css class that I don't want to add into every li tag. It should be added into one li and next li should be empty and so on...
I tried to add
for example
```
<?php
$css_class = 'class="pull_rigt"';
echo "<ul>";
foreach($posts as $key => $value ) {
echo "<li $css_class>";
echo $value['data'];
echo "</li>";
}
echo "<ul>";
?>
```
the output should be
```
<li class="pull_rigt">
data
<li>
<li>
data
</li>
```
I tried matching power of two numbers in every foreach index but couldn't figure out the math.
```
<?php
$css_class = 'class="pull_rigt"';
echo "<ul>";
$i = 0;
foreach($posts as $key => $value ) {
<li <?php echo ($i & ($i - 1)) == 0 ? $css_class; ?>
echo $value['data'];
echo "</li>";
$i++;
}
echo "<ul>";
?>
``` | 2015/05/05 | [
"https://Stackoverflow.com/questions/30056024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1122893/"
] | Most simple solution might be using [nth-child selector](http://www.w3schools.com/cssref/sel_nth-child.asp), so that you don't need to use any classes at all.
Or, use % operator in PHP - it means "remainder after division by some number".
The foreach loop could look like this:
```
foreach ($posts as $key=>$value) {
echo "<li"
if ($key % 2 == 1) { // For $key 1, 3, 5, 7...
echo " ".$css_class;
}
echo ">";
echo $value["data"];
echo "</li>";
}
```
Use different operands to get different results, i.e. `$key % 3 == 2` would be truthy for $key 2, 5, 8 etc. | I use the modulus operator `%` for these things.
<http://php.net/language.operators.arithmetic>
For simple even/odd evaluations:
**Even:** `$num % 2 == 0`
**Odd:** `$num % 2 == 1`
Here's a standalone example based on your code:
```
<?php
// Test Data
$posts = array();
for ($i = 0; $i < 10; $i++) {
$posts[] = array('data' => $i);
}
echo '
<style type="text/css">
.pull_rigt {
color: red;
}
</style>';
// UL
echo "<ul>";
$i = 0;
foreach($posts as $key => $value ) {
$class = ($i % 2 == 0) ? ' class="pull_rigt"' : ''; // Even Numbers
#$class = ($i % 2 == 1) ? ' class="pull_rigt"' : ''; // Odd Numbers
echo "<li{$class}>";
echo $value['data'];
echo "</li>";
$i++;
}
echo "<ul>";
?>
```
You can see it working here: <http://viper-7.com/t0jUn1> |
46,636,056 | I installed ruby on Ubuntu for system-wide use. The `.irbrc_history` file is created in a system directory rather than the user's home directory. This causes an access error when the file is owned by someone else. Here's the error besides a bunch more that I think is irrelevant:
```
irb
/usr/local/rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/irb/ext/save-history.rb:75:in `initialize': Permission denied @ rb_sysopen - /usr/local/rvm/rubies/ruby-2.4.1/.irbrc_history (Errno::EACCES)
```
Deleting the history file resolves the error.
I tried adding environment variables and history initialization code to what I think is the system `.irbrc` file, but to no avail.
What is the sequence of initialization files being executed that impact this history file? How can I change the location of the history file? | 2017/10/08 | [
"https://Stackoverflow.com/questions/46636056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8742573/"
] | Create, or edit your ~/.irbrc file to include:
```
require 'irb/ext/save-history'
IRB.conf[:SAVE_HISTORY] = 200
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-history"
```
Source: [How To Persist Rails or IRB Console Command History After Exit](http://%20https://jdc.io/how-to-persist-rails-or-irb-console-command-history-after-exit) | Do you happen to use RVM?
rvm 1.29.3 (current stable) has a bug where IRB history gets saved in the `RUBY_HOME` instead of `HOME`.
<https://github.com/rvm/rvm/issues/4158>
Here's a fix:
```
rvm get head
rvm reinstall 2.4.1
``` |
4,962,916 | Should I put a Semicolon (`;`) when I use `onclick=""`?
```
<p onclick="closeLightBox();">Click<p>
```
or:
```
<p onclick="closeLightBox()">Click<p>
``` | 2011/02/10 | [
"https://Stackoverflow.com/questions/4962916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/423903/"
] | The semicolon in this position, is valid, but not mandatory. | I prefer a semicolon. I know it is optional (as it is many times in JS), but I like to be uniform and it helps to alert the person that the statement is complete. |
6,496,931 | This is my array:
```
array = [:one,:two,:three]
```
I want to apply `to_s` method to all of my array elements to get `array = ['one','two','three']`.
How can I do this (converting each element of the enumerable to something else)? | 2011/06/27 | [
"https://Stackoverflow.com/questions/6496931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/774177/"
] | This will work:
```
array.map!(&:to_s)
``` | You can use [`map`](http://www.ruby-doc.org/core/classes/Array.html#M000249) or [`map!`](http://www.ruby-doc.org/core/classes/Array.html#M000250) respectively, the first will return a new list, the second will modify the list in-place:
```
>> array = [:one,:two,:three]
=> [:one, :two, :three]
>> array.map{ |x| x.to_s }
=> ["one", "two", "three"]
``` |
25,054,457 | This is related to this question: [Can I import a TypeScript class from my own module to global?](https://stackoverflow.com/questions/24861405/can-i-import-a-typescript-class-from-my-own-module-to-global)
I have made a module and I want to expose a class to the global scope.
```
module Foo {
export class Bar {
x: number
}
/* Some more interfaces and classes to be used only in this module */
}
```
At first, I made an interface and defined a new variable to achieve this.
```
interface Bar extends Foo.Bar {
}
var Bar = Foo.Bar;
```
The generated JavaScript had my Bar as a variable.
```
var Foo;
(function (Foo) {
var Bar = (function () {
function Bar() {
}
return Bar;
})();
Foo.Bar = Bar;
})(Foo || (Foo = {}));
var Bar = Foo.Bar;
//# sourceMappingURL=app.js.map
```
The d.ts file included my global Bar interface and variable.
```
declare module Foo {
class Bar {
public x: number;
}
}
interface Bar extends Foo.Bar {
}
declare var Bar: typeof Foo.Bar;
```
Then, **I noticed that I can simply use `import` to expose my class**, and I did so.
```
import Bar = Foo.Bar;
```
The resulting JavaScript file was exactly same.
```
var Foo;
(function (Foo) {
var Bar = (function () {
function Bar() {
}
return Bar;
})();
Foo.Bar = Bar;
})(Foo || (Foo = {}));
var Bar = Foo.Bar;
//# sourceMappingURL=app.js.map
```
However, my d.ts file now does not include any information about the global Bar.
```
declare module Foo {
class Bar {
public x: number;
}
}
```
Is this an intended result? I think this would cause errors, as it would allow declaring variables with the same name, when I include the JavaScript file and d.ts file in other project. | 2014/07/31 | [
"https://Stackoverflow.com/questions/25054457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2460034/"
] | This turns out to be a bug in current compiler, and new compiler seems to have fixed this. See: <https://github.com/Microsoft/TypeScript/issues/346>
Corrected declaration:
```
declare module Foo {
class Bar {
x: number;
}
}
import Bar = Foo.Bar;
``` | When you use an import statement, the compiler assumes that the definition is elsewhere.
For example, if you imported something from `fileA.ts` into `fileB.ts`, the generated `fileA.d.ts` would already contain the declaration, which would then conflict with `fileB.d.ts` if it also included the declaration.
So I would say that this behaviour is intentional. |
154,980 | This seems to work fine, but I'm very new to C++ and would like any suggestions for improvements. Areas I have the most trouble with are:
* Namespacing (honestly, it's still half looking stuff up and making an educated guess with typename blah blah blah). Is there a "cleaner" way to implement this?
* Various C++ idioms (copy and swap) that aren't as common in, say, C or Java. There are good answers relating to copy and swap in particular, but I just don't quite "get it" yet. The principal makes sense, but specifically what to do with regards to protecting against exceptions in the copy constructor itself
* Adding to that, exceptions in general in C++ (coming from the strict Java approach and the "check errno/return value/whatever" C approach), although in the context of this code it's more about guaranteeing exception safety where people would expect it (see above).
* General good "style". Specifically, what's the cleanest way to implement the `Node` class in data structures where we see something like this? this plays into how namespacing can get tricky. There seems to be a tradeoff of encapsulation (e.g. defining a struct node within the LinkedList class seems intuitively more "reasonable", but this makes dealing with nodes in any function that may be written outside my definition file strewn with typename).
+ Another example: should `root` really be a `unique_ptr` here instead of a regular object? It certainly made my code easier to write, but I'm curious as to arguments for or against it.
* I'm still fairly unclear as to when exactly I need the template declaration for classes (see the copy constructor for instance, where it takes `LinkedList` as an argument instead of `LinkedList<T>`, but it worked, which seems odd).
I understand the use case between e.g. unique\_ptr and shared\_ptr for the most part, but certainly want to know if I'm misusing anything here. There is nothing fancy (like a reference to the tail to make insertion faster), but I just want to make sure I'm starting out on the right foot as the more I use C++ it seems the less I actually understand anything.
LinkedList class header
-----------------------
```
#ifndef _NEW_LL_H
#define _NEW_LL_H
#include<memory>
#include "node.h"
template <typename T>
class LinkedList {
public:
LinkedList() {};
~LinkedList() {}; // destructor
LinkedList(LinkedList const & ll); // copy constructor
LinkedList& operator=(LinkedList const & ll); // copy assignment
LinkedList(LinkedList && ll); // move constructor
LinkedList& operator=(LinkedList && ll); // move assignment
void append(T const& item);
// deletes the first node containing item, returns true if successful
bool delete_node(T const& item);
void print();
bool search(T const& item);
std::unique_ptr<typename Node<T>::Node> root;
// std::unique_ptr<Node> tail; maybe later
};
#endif
```
Node header
-----------
```
#ifndef _NODE_H
#define _NODE_H
#include<memory>
template <typename T>
class Node {
public:
T item;
std::unique_ptr<Node> next=nullptr;
Node(T const& t); // default constructor
Node(Node const& insert); // copy constructor
};
#endif
```
Implementation file
-------------------
```
#include <iostream>
#include <memory>
#include "new_ll.h"
using namespace std;
template <typename T>
LinkedList<T>::LinkedList(LinkedList const & ll) {
if(ll.root) root = make_unique<Node<T>>(*ll.root);
} // copy constructor calls node's recursively
template <typename T>
LinkedList<T>& LinkedList<T>::operator=(LinkedList<T> const & ll) {
if(ll.root) root = make_unique<Node>(*ll.root);
} // copy assignment
template <typename T>
LinkedList<T>::LinkedList(LinkedList<T> && ll) {
root = move(ll.root);
} // move constructor
template <typename T>
LinkedList<T>& LinkedList<T>::operator=(LinkedList<T> && ll) {
root = move(ll.root);
} // move assignment
template <typename T>
void LinkedList<T>::append(T const& item) {
if(root==nullptr) {
root = make_unique<Node<T>>(item);
return;
}
Node<T> *tmpNode = root.get();
while(tmpNode->next!=nullptr) tmpNode=tmpNode->next.get();
tmpNode->next = make_unique<Node<T>>(item);
}
template <typename T>
bool LinkedList<T>::delete_node(T const& item) {
if(root->item == item) {
root = move(root->next);
return true;
}
Node<T> *tmpNode = root.get();
while(tmpNode->next!=nullptr) {
if(tmpNode->next->item == item) {
tmpNode->next = move(tmpNode->next->next);
return true;
}
tmpNode = tmpNode->next.get();
}
return false;
}
template <typename T>
void LinkedList<T>::print() {
Node<T> *tmpNode = root.get();
while(tmpNode!=nullptr) {
cout << "Address: " << tmpNode << " value: " << tmpNode->item << endl;
tmpNode = tmpNode->next.get();
}
}
template <typename T>
bool LinkedList<T>::search(T const& item) {
Node<T> *tmpNode = root.get();
while(tmpNode!=nullptr) {
if(tmpNode->item == item) return true;
tmpNode = tmpNode->next.get();
}
return false;
}
template <typename T>
Node<T>::Node(T const& t) : item(t) {}; // default constructor
template <typename T>
Node<T>::Node(Node const& insert) : item(insert.item) {
if(insert.next) next = make_unique<Node<T>>(*insert.next);
}; // copy constructor
```
Any input is appreciated! I just feel like an idiot as I seem to constantly be learning and forgetting "good" C++ practice. | 2017/02/10 | [
"https://codereview.stackexchange.com/questions/154980",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/130631/"
] | ### LinkedList Header
Don't use identifiers with a leading underscore:
```
#ifndef _NEW_LL_H
#define _NEW_LL_H
```
These two are not valid (reserved for the implementation).
Header inclusion order:
```
#include<memory>
#include "node.h"
```
I always do most specific to least. So your local header files first. Then C++ header files. Then C header files. Also add a space before `<memory.h>`.
Put the `&` with the type (its part of the type information).
```
LinkedList(LinkedList const & ll); // copy constructor
LinkedList& operator=(LinkedList const & ll); // copy assignment
LinkedList(LinkedList && ll); // move constructor
LinkedList& operator=(LinkedList && ll); // move assignment
```
You have a normal append.
```
void append(T const& item);
```
But your list is move aware. So it seems like you should be able to move elements into the list.
```
void append(T&& item);
template<typename... Args>
void append(Args&&... args); // append item but use its constructor.
```
### Node Header
Don't use identifiers with a leading underscore:
```
#ifndef _NODE_H
#define _NODE_H
```
These two are not valid (reserved for the implementation).
You have normal constructors:
```
Node(T const& t); // default constructor
Node(Node const& insert); // copy constructor
```
But what about the move constructors.
```
Node(Node&& move);
```
### Source File review:
Don't do this:
```
using namespace std;
```
Its short for a reason. Adding `std::` as a prefix is not that much of a burden. Get used to it. Also worth a read [Why is “using namespace std” considered bad practice?](https://stackoverflow.com/a/1453605/14065). It will explain in detail why it is bad practice.
This does not work if the source is empty.
```
template <typename T>
LinkedList<T>& LinkedList<T>::operator=(LinkedList<T> const & ll) {
if(ll.root) root = make_unique<Node>(*ll.root);
} // copy assignment
```
This means if you try and copy a list (that happens to be empty) nothing happens. Which is not what you want. If the source is empty then you want your list to become empty (not keep its current content). just convert to using the copy and swap idiom.
Prefer to use the initializer list than the body.
```
template <typename T>
LinkedList<T>::LinkedList(LinkedList<T> && ll) {
root = move(ll.root);
} // move constructor
```
Here you are basically initializing root with `nullptr` then immediately assigning over it.
You can simplify this a lot. It should not matter if the root is `nullptr` or not. You are always adding to a thing that is `unique_ptr<Node>`. Just find the correct one then call `make_unique()`
```
template <typename T>
void LinkedList<T>::append(T const& item) {
if(root==nullptr) {
root = make_unique<Node<T>>(item);
return;
}
Node<T> *tmpNode = root.get();
while(tmpNode->next!=nullptr) tmpNode=tmpNode->next.get();
tmpNode->next = make_unique<Node<T>>(item);
}
```
Your delete is basically a `search()` followed by a delete. Why not reduce redundant code by moving the search into its own private `doSearch()` function that returns a `Node*`. Then the public functions can use this private function and return the appropriate value.
```
template <typename T>
bool LinkedList<T>::delete_node(T const& item) {
if(root->item == item) {
root = move(root->next);
return true;
}
Node<T> *tmpNode = root.get();
while(tmpNode->next!=nullptr) {
if(tmpNode->next->item == item) {
tmpNode->next = move(tmpNode->next->next);
return true;
}
tmpNode = tmpNode->next.get();
}
return false;
}
```
If you are going to print. Then a least allow the user to specify what stream you want to print too (you can provide a default version):
```
template <typename T>
void LinkedList<T>::print(std::ostream& out = std::cout)
{
}
```
Note the default way to print something in C++ is to use the `operator<<` so you may as well define one of those while you are at it:
```
frined std::ostream& operator<<(std::ostream& str, LinkedList const& list)
{
list.print(str);
return str;
}
``` | In addition to what @MartinYork said, I have a few comments.
```
std::unique_ptr<typename Node<T>::Node> head;
```
Why don't you just say:
```
std::unique_ptr<Node<T>> head;
```
Inside a class, you don't have to specify any template parameters when using that class type. The compiler automatically assumes you are talking about `LinkedList<T>`.
Also, check out `std::forward_list<T>` [here](https://en.cppreference.com/w/cpp/container/forward_list). |
16,779,324 | I want my app to store the user's data remotely when they sign up (possibly in a MySQL database). I have seen tutorials about retrieving data through MySQL and JSON, but I cannot seem to find anything about storing data into the MySQL database. Maybe this isn't the best way to do it? | 2013/05/27 | [
"https://Stackoverflow.com/questions/16779324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/939636/"
] | Your question is a bit too vague to be able to answer implementation details, so I give an outline how I would go about the problem:
1. Determine if you want to create the service yourself or use a cloud data storage provider (some are free and provide iOS libraries. One simple example is Apple's own iCloud).
2. If you create your own service, use your favorite Web technology. Have a look at [Tastypie](http://django-tastypie.readthedocs.org/en/latest/) for example.
3. Use a RESTful iOS client library such as [RESTkit](http://restkit.org) to connect to your service.
If you don't have any specific requirements, I would start by investigating if Core Data + iCloud fits the requirements. That should get you up and running in the shortest time. | I think you can call a .php page from your app like below:
```
NSString *urlWithGetVars=@"http://www.somedomain.com/somepage.php?var1=avar&var2=anothervar";
NSURL *url = [NSURL URLWithString:urlWithGetVars];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
//turn response data to string
NSString *responseString = [[NSString alloc]
initWithData:responseData
encoding:NSUTF8StringEncoding];
//check if there is any error
if(!error)
{
//log the response
NSLog(@"Response from server = %@", responseString);
}
else
{
//log error
NSLog(@"Error = %@",error.description);
}
```
And in your somepage.php do the data writing process to the MySql database like below:
```
<?php
$var1=$_GET["var1"];
$var2=$_GET["var2"];
// Make a MySQL Connection
mysql_connect("yoursitehost", "usr", "pass") or die(mysql_error());
mysql_select_db("yourdb") or die(mysql_error());
// Write var1 and var2 to your mysql table
mysql_query("INSERT INTO your_table (var1,var2) VALUES ('".$var1."','".$var2."')");
or die(mysql_error());
?>
```
There might be some coding errors if you notice anything wrong let me know...
PS: NSURLConnection sendSynchronousRequest is going to block the user interface so you probably don't want to use it |
32,249,416 | I have two folder inside same folder as below :-
1.src (it contains my cpp file)
2.linux (where I am running g++ and executing o file)
now I am running commands as below
```
cd linux
g++ --coverage ../src/example1.cpp -o example1
./example1
cd ..
/opt/gcovr-3.2//scripts/gcovr -v -r .
```
I got output as, with 0% coverage
>
> Scanning directory . for gcda/gcno files...
>
>
>
>
To debug further, I goto 'linux' folder as run below command
```
gcov /opt/gcovr-3.2/doc/examples/example1/linux/example1.gcno --branch-counts --branch-probabilities --preserve-paths --object-directory /opt/gcovr-3.2/doc/examples/example1/linux
```
I got output as, with valid coverage
>
> /opt/gcovr-3.2/doc/examples/example1/linux
>
> File '../src/example1.cpp'
>
> Lines executed:85.71% of 7
>
> Branches executed:100.00% of 2
>
> Taken at least once:50.00% of 2
>
> Calls executed:100.00% of 1
>
> ../src/example1.cpp:creating '..#src#example1.cpp.gcov'
>
>
>
>
Now I want to know what wrong I am doing? my project is complex, so I don't want to do copy all cpp files from respective 'src' folder to respective 'linux' folder. I tried with `--object-directory` then also same result. | 2015/08/27 | [
"https://Stackoverflow.com/questions/32249416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5272378/"
] | gcovr uses .gcov files for analysis.
I also faced similar issue and overcame it in 2 steps by manually generating .gcov file
1. In the folder which contains gcno files run `gcov -b -l -p -c *.gcno`
This will generate gcov files with all details from gcno and gcda files.
2. Go to Project Root Folder and run `gcovr -g -k -r . --html --html-details -o tp.html` or any gcovr command with -g option, -g option tells gcovr to process gcov output files
Hope this solution Helps.. | If applicable, turn off [ccache](https://ccache.dev/).
If ccache ever does its thing (let's say you wiped the build directory), it will happily restore the object files from cache while not restoring the `*.gcno` files, because it doesn't know about those. |
3,478,041 | My Python (2.6) installation on a few servers has been compiled without curses support which I now need, although the servers have libncurses5 installed, Python did not compile the bindings for it so when I "import curses" I get:
```
"ImportError: No module named _curses"
```
my /lib/ dir has the following files and symlinks:
```
lrwxrwxrwx 1 root root 17 2010-02-13 05:50 /lib/libncurses.so.5 -> libncurses.so.5.7
-rw-r--r-- 1 root root 251K 2008-12-14 22:31 /lib/libncurses.so.5.7
lrwxrwxrwx 1 root root 18 2010-02-13 05:50 /lib/libncursesw.so.5 -> libncursesw.so.5.7
-rw-r--r-- 1 root root 299K 2008-12-14 22:31 /lib/libncursesw.so.5.7
```
and /lib64/ has:
```
lrwxrwxrwx 1 root root 20 2010-08-13 12:26 /lib64/libncurses.so -> /lib/libncurses.so.5
lrwxrwxrwx 1 root root 17 2010-02-13 05:50 /lib64/libncurses.so.5 -> libncurses.so.5.7
-rw-r--r-- 1 root root 251K 2008-12-14 22:31 /lib64/libncurses.so.5.7
lrwxrwxrwx 1 root root 18 2010-02-13 05:50 /lib64/libncursesw.so.5 -> libncursesw.so.5.7
-rw-r--r-- 1 root root 299K 2008-12-14 22:31 /lib64/libncursesw.so.5.7
```
/usr/lib64 and /usr/lib both have have :
```
lrwxrwxrwx 1 root root 20 2010-08-13 12:20 /usr/lib64/libncurses.so -> /lib/libncurses.so.5
```
When I try to 'make' python again, I get back at the end the following warning:
```
Failed to find the necessary bits to build these modules:
_curses_panel _tkinter bsddb185
bz2 dl gdbm
imageop readline sunaudiodev
To find the necessary bits, look in setup.py in detect_modules() for the module's name.
Failed to build these modules:
_curses
```
What do I need to do to recompile Python with curses support? What am I missing here?
Thanks! | 2010/08/13 | [
"https://Stackoverflow.com/questions/3478041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159241/"
] | I'm not sure which of these actions resolved my problem but one of them did. I installed libncurses5-dev and libreadline5-dev, recompiled python and reinstalled (make / make install).
Huzza | Yes, that's right. Installing `libncurses5-dev` and running `'make'` and `'make install'` on the `python` installation did the trick. I had encountered the error with `_curses` first while trying to install and fire up `bpython` on my custom python installation. |
47,817,703 | What would be the most idiomatic way to find the days with a drawdown greater than X bips? I again worked my way through some queries but they become boilerplate ... maybe there is a simpler more elegant alternative:
```
q)meta quotes
c | t f a
----| -----
date| z
sym | s
year| j
bid | f
ask | f
mid | f
```
then I do:
```
bips:50;
`jump_in_bips xdesc distinct select date,jump_in_bips from (update date:max[date],jump_in_bips:(max[mid]-min[mid])%1e-4 by `date$date from quotes where sym=accypair) where jump_in_bips>bips;
```
but this will give me the days for which there has been a jump in that number of bips and not only the drawdowns.
I can of course put this result above in a temporary table and do several follow up selects like:
```
select ... where mid=min(mid),date=X
select ... where mid=max(mid),date=X
```
to check that the `max(mid)` was *before* the `min(mid)` ... is there a simpler, more idiomatic way? | 2017/12/14 | [
"https://Stackoverflow.com/questions/47817703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1142881/"
] | I think `maxs` is the key function here, which allows you to maintain a running historical maximum, and you can compare your current value to that maximum. If you have some table `quote` which contains some series of mids (`mids`) and timestamps (`date`), the following query should return the days where you saw a drawdown greater than a certain value:
```
key select by `date$date from quote
where bips<({(maxs[x]-x)%1e-4};mid) fby `date$date
```
The lambda `{(maxs[x]-x)%1e-4}` is doing the comparison at each point to the historical maximum and checking if it's greater than `bips`, and `fby` lets you apply the `where` clause group-wise by date. Grouping with a `by` on date and taking the key will then return the days when this occurred.
If you want to preserve the information for the max drawdown you can use an update instead:
```
select max draw by date from
(update draw:(maxs[mid]-mid)%1e-4 by date from @[quote;`date;`date$])
where bips<draw
```
The date is updated separately with a direct modification to quote, to avoid repeated casting. | Difference between `max` and `min` mids for given date may be both increase and drawdown. Depending on if `max` mid precedes `min`. Also, as far a `sym` columns exists, I assume you may have different symbols in the table and want to get drawdowns for all of them.
For example if there are 3 quotes for given day and sym: `1.3000 1.2960 1.3010`, than the difference between 2nd and 3rd is 50 pips, but this is increase.
The next query can be used to get dates and symbols with drawdown higher than given threshold
```
select from
(select drawdown: {max maxs[x]-x}mid
by date, sym from quotes)
where drawdown>bips*1e-4
```
`{max maxs[x]-x}` gives maximum drawdown for given date by subtracting each mid for maximum of preceding mids. |
39,133,983 | I am trying to construct a raw `json` string as below to send it out in http request
```
var requestContent = @"{
""name"": ""somename"",
""address"": ""someaddress""
}";
```
Instead of having name and address value hardcoded I was hoping to supply them from below variables
```
string name = "someName";
string address = "someAddress";
```
But the below does not work. Any idea ?
```
var requestContent = @"{
""name"": \" + name \",
""address"": \" + address \"
}";
``` | 2016/08/24 | [
"https://Stackoverflow.com/questions/39133983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258956/"
] | You could use a verbatim string together with interpolation as well:
```
var requestContent = $@"{{
""name"": ""{name}"",
""address"": ""{address}""
}}";
```
EDIT: For this to work you have to make sure that curly braces you want in the output are doubled up (just like the quotes). Also, first `$`, then `@`. | Instead use [`Newtonsoft.JSON JObject()`](http://www.newtonsoft.com/json/help/html/CreateJsonDynamic.htm) like
```
dynamic myType = new JObject();
myType.name = "Elbow Grease";
myType.address = "someaddress";
Console.WriteLine(myType.ToString());
```
Will generate JSON string as
```
{
"name": "Elbow Grease",
"address": "someaddress"
}
``` |
6,625,920 | We use SVN for a giant server of design assets at my job. I like to keep the root of our server checked out, so I can get organizational updates to the directory hierarchy as they're made. But their are certain directories within that I won't ever be touching... and they're huge... 15 gb+.
I want to rm these directories, and have them not pull back down when I svn up from the root. Is this possible? | 2011/07/08 | [
"https://Stackoverflow.com/questions/6625920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428741/"
] | What you need is not to ignore these folders (since ignoring means setting them out of repository), but to control the depth of checkout.
You can checkout your root with **--depth immediates** option this will only checkout subfolders of the root dir. Then go inside and do the same with folders you need or checkout with **--depth infinity** directory you are interested in.
PS
GUI svn clients like [TortoiseSVN](http://www.igorexchange.com/node/87) make this process more convenient. | ```
svn propset svn:ignore <dir>
```
Will ignore the dir. |
50,377,720 | In Python, i need to split two rows in half, take the first half from row 1 and second half from row 2 and concatenate them into an array which is then saved as a row in another 2d array. for example
```
values=np.array([[1,2,3,4],[5,6,7,8]])
```
will become
```
Y[2,:]= ([1,2,7,8])) // 2 is arbitrarily chosen
```
I tried doing this with concatenate but got an error
**only integer scalar arrays can be converted to a scalar index**
```
x=values.shape[1]
pop[y,:]=np.concatenate(values[temp0,0:int((x-1)/2)],values[temp1,int((x-1)/2):x+1])
```
temp0 and temp1 are integers, and values is a 2d integer array of dimensions (100,x) | 2018/05/16 | [
"https://Stackoverflow.com/questions/50377720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9801877/"
] | Try numpy.append
[numpy.append Documentation](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.append.html)
```
np.append(values[temp0,0:int((x-1)/2)],values[temp1,int((x-1)/2):x+1])
``` | You don't need splitting and/or concatenation. Just use [*indexing*](https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html):
```
In [47]: values=np.array([[1,2,3,4],[5,6,7,8]])
In [48]: values[[[0], [1]],[[0, 1], [-2, -1]]]
Out[48]:
array([[1, 2],
[7, 8]])
```
Or ravel to get the flattened version:
```
In [49]: values[[[0], [1]],[[0, 1], [-2, -1]]].ravel()
Out[49]: array([1, 2, 7, 8])
```
As a more general approach you can also utilize `np.r_` as following:
```
In [61]: x, y = values.shape
In [62]: values[np.arange(x)[:,None],[np.r_[0:y//2], np.r_[-y//2:0]]].ravel()
Out[62]: array([1, 2, 7, 8])
``` |
34,530,231 | IntelliJ Idea fold if and other statements in JavaScript, but not in Java. How can I get this feature? Maybe you know some plugin or settings? | 2015/12/30 | [
"https://Stackoverflow.com/questions/34530231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5648942/"
] | In Android Studio, in order to fold a try/catch structure -
1. In the editor window, select the left brace after try
2. Type on keyboard `CTRL` + `Shift` + `.`
Now the complete try { .. } block will be folded. | If I want to reduce a try / catch section, it doesn't work for me on Intellij CI 2016, under Ubuntu 16.04 OS.
Even with shortcut or using menus.
Using menus Code > Folding > Fold Selection / Remove Section ( `Ctrl` + Period, where Period is the `.`), it'll close the entire function where the try/catch block is.
It doesn't work either if I use shortcut `Ctrl`+ `Shift` + `.`
Seems to be a conflict with other shortcut existing on the OS I'm running onto. |
52 | Questions such as removing viruses or malware, help installing/uninstalling software, configuring Outlook, etc? | 2009/04/30 | [
"https://meta.serverfault.com/questions/52",
"https://meta.serverfault.com",
"https://meta.serverfault.com/users/-1/"
] | If there related to a multi pc environment - such as having a virus affect your whole network or setting up outlook for multiple pc's then that should be ok. 1 Pc with a virus or email error is not really what SF's about, but they will come, I guess the only way to deal with that is good moderation.
I think this will be more of a problem than with SO, as everyone has a pc, when they experience a problem there going to google it and SF will be here with an answer thats close, but doesn't really apply because its for a server, so they'll ask the question instead. | I think this is the biggest risk for serverfault.
Stackoverflow only has to contend with homework and 'give me teh codes pleez' questions. But the world is full of more or less clueless people with PCs who do know how to use Google...
This is where the low barrier to entry (no login required) could become a problem, long term. I guess rep may be the saving factor, as clueless people aren't likely to get much. I expect that once serverfault gets to a critical mass of questions/users, the downvoting and closing will become a lot harsher, as the community becomes more engaged and will want to protect the value of the site.
So in short I would answer - ask away for the time being. If your question is for your home PC but is also of relevance/interest to a sysadmin, I don't think there's a problem. |
24,969,522 | I am trying to write to a txt file from a JAVA Application. I have tried using Buffered Writer, then just FileWriter to create a new file within a potentially new (not indefinitely since more files with different names will be later programatically written there by the same method) subfolder. I get the following error message (It's actually much longer but I think this is the key part of it):
>
> java.io.FileNotFoundException: src/opinarium3/media/presentaciones/Los
> fantasmas del Sistema Solar/comments/2014-07-26.txt (No such file or
> directory) at java.io.FileOutputStream.open(Native Method)
>
>
>
And this is the code firing the issue (it activates as you press a button to register a comment having been filled in a custom form):
```
private void fileCommentOnPresentation(String title, String positiveComments, String negativeComments, int grade) throws IOException{
FileWriter bw;
try{
bw = new FileWriter("src/opinarium3/media/presentaciones/"+title+"/comments/"+Date.valueOf(LocalDate.now())+".txt");
bw.write(title+"\n"+positiveComments+"\n"+negativeComments+"\n"+grade);
bw.flush();
bw.close();
}catch(IOException e){
e.printStackTrace();
}
}
``` | 2014/07/26 | [
"https://Stackoverflow.com/questions/24969522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3855264/"
] | Looking at
```
new FileWriter("src/opinarium3/media/presentaciones/"+title+"/comments/...")
```
I see that you are trying to introduce a directory from variable title. Not sure whether this creates all missing directories. So please make sure that this directory exists and create it before writing to the file two levels below. | You can try any one based on file location. Just use prefix `/` to start looking into `src` folder.
```
// Read from resources folder parallel to src in your project
File file1 = new File("resources/abc.txt");
System.out.println(file1.getAbsolutePath());
// Read from src/resources folder
File file2 = new File(getClass().getResource("/resources/abc.txt").toURI());
System.out.println(file2.getAbsolutePath());
```
**Note:** Try to avoid spaces in the path.
First check whether folder(directory) exists or not:
sample code:
```
File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
...
}
```
[Read more...](https://stackoverflow.com/questions/15571496/how-to-check-if-a-folder-exists) |
25,982,325 | I am starting to follow [this](http://ionicframework.com/docs/guide/installation.html) demo for learning the ionic framework.
I made it to the point where it suggests that I type in `ionic platform android`. When I type that, I get this error:
```
C02FF724DF91:todo jcorser$ ionic platform android
Creating android project...
/Users/jcorser/.cordova/lib/npm_cache/cordova-android/3.6.3/package/bin/node_modules/q/q.js:126
throw e;
^
Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.
at /Users/jcorser/.cordova/lib/npm_cache/cordova-android/3.6.3/package/bin/lib/check_reqs.js:158:19
at _fulfilled (/Users/jcorser/.cordova/lib/npm_cache/cordova-android/3.6.3/package/bin/node_modules/q/q.js:798:54)
at self.promiseDispatch.done (/Users/jcorser/.cordova/lib/npm_cache/cordova-android/3.6.3/package/bin/node_modules/q/q.js:827:30)
at Promise.promise.promiseDispatch (/Users/jcorser/.cordova/lib/npm_cache/cordova-android/3.6.3/package/bin/node_modules/q/q.js:760:13)
at /Users/jcorser/.cordova/lib/npm_cache/cordova-android/3.6.3/package/bin/node_modules/q/q.js:821:14
at flush (/Users/jcorser/.cordova/lib/npm_cache/cordova-android/3.6.3/package/bin/node_modules/q/q.js:108:17)
at process._tickCallback (node.js:419:13)
at Function.Module.runMain (module.js:499:11)
at startup (node.js:119:16)
at node.js:906:3
Error: /Users/jcorser/.cordova/lib/npm_cache/cordova-android/3.6.3/package/bin/create: Command failed with exit code 8
at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:135:23)
at ChildProcess.emit (events.js:98:17)
at maybeClose (child_process.js:755:16)
at Process.ChildProcess._handle.onexit (child_process.js:822:5)
```
I am on Mac OSX. I have developed two android apps before using Android Studio. I also followed the suggestion for OSX on the manual `$ export JAVA_HOME=$(/usr/libexec/java_home)` but this did not fix the problem. | 2014/09/22 | [
"https://Stackoverflow.com/questions/25982325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3779669/"
] | On windows set the `ANDROID_HOME` in System Variables | If you installed Android SDK via Homebrew, then fix this:
```
export ANDROID_HOME=`brew --prefix android`
``` |
41,537,283 | I'm using a library called DS3231 by rinkydinkelectronics
Link: <http://www.rinkydinkelectronics.com/library.php?id=73> (click on manual)
i'm trying to run the following code
```
String alarmTime = "08:52:00";
void loop(){
if (rtc.getTimeStr() == alarmTime){
alarmState = true;
}
}
```
but i get the following error:
>
> exit status 1 no match for 'operator==' (operand types are 'char\*' and
> 'String')
>
>
>
the library manual however says that the return value is a string so I don't see why this shouldn't work :(
Can someone help me fix this or tell me what might be wrong?
Thank you! | 2017/01/08 | [
"https://Stackoverflow.com/questions/41537283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6229886/"
] | If understood your code right, you want to check whether both strings are equal. Because the standard library is not available in the Arduino IDE, you must choose a different way. Convert the C string (`char*`) to a [`String` object](https://www.arduino.cc/en/Reference/StringLibrary).
Example:
```
if(String(rtc.getTimerStr()) == alarmTime) {
....
}
```
This should work. | You're trying to compare two different things with confusingly similar names. A [string](https://www.arduino.cc/en/Reference/String)(C style string) is a null terminated char array. This is different from the [String object](https://www.arduino.cc/en/Reference/StringObject). It's generally accepted that with extremely memory limited hardware such as the standard Arduino boards you should avoid the use of the String class if possible as it uses more memory and may cause memory fragmentation from dynamic memory allocation. Much better to use strings instead, which are actually pretty much just as easy to work with as String.
Your code using only strings:
```cpp
char alarmTime[] = "08:52:00";
void loop() {
if (strcmp(rtc.getTimeStr(), alarmTime) == 0) {
alarmState = true;
}
}
``` |
611,357 | I have a beginners question in T-SQL.
We imported Excel Sheets into a SQL Server 2008. Too bad these Excel files were not formatted the way they should be. We want a phone number to look like this: '012345678', no leading and trailing whitespace and no whitespace within. Even worse sometimes the number is encoded with a prefix '0123-2349823' or '0123/2349823'.
Normally I would export the Excel file to a [CSV](http://en.wikipedia.org/wiki/Comma-separated_values) file, then launch some magic Perl script to do the cleaning and then reimport the Excel file.
Still it would be interesting to know how to do stuff like this with T-SQL.
Any ideas? | 2009/03/04 | [
"https://Stackoverflow.com/questions/611357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132162/"
] | Something like
```
replace(replace(rtrim(ltrim('0123-2349823')), '-', ''), '/', '')
```
should work. Doesn't look pretty. ;) | I would go about it with an update and use the 'Replace' and LTrim/RTrim functions for SQL.
```
Update Table1
set phonenum = Case
When phonenum like '%-%' Then LTrim(RTrim(Replace(phonenum, '-', '')))
Else LTrim(RTrim(Replace(phonenum, '/', '')))
End
``` |
437,210 | Has anyone ever transcoded music from a high-quality aac to an mp3 (or vice-versa). The internet is full of people who say this should never be done, but apart from the theoretical standpoint that you can only lose information, does it matter in practise?
* is the difference perceivable, except on studio-equipment?
* does the re-encoding actually lose much information? If, p.e., high frequences are chopped away by the initial compression, those frequencies aren't there anymore, so this part of the compression-algorithm won't touch the data during the second compression. Am i wrong? | 2012/06/15 | [
"https://superuser.com/questions/437210",
"https://superuser.com",
"https://superuser.com/users/76106/"
] | It'll really depend on what the nature of the audfio, the hearing of the person involved, the gear *and* both psycological and psycoacoustic models.
Basically different psycoacoustic models discard different types of signals, so you'd lose *different* things.
I'd avoid it personally, but if you *had* to do it, you probably have equipment that isn't that great to start with, and you might not notice - I can't tell the difference between flac and 320vbr on most soundcards, or which tracks i may have reconverted in the past.
I've done similar things in the past (downsampling music) and honestly, on most gear, i can't tell the difference. I'd say try it, test it double blind, and in most cases, you wouldn't be able to tell. | Information will inevitably be lost, but unless you're an audiophile using top-grade equipment, the difference will likely not be noticeable.
Conversion of any data, whether or not it is already in a lossy format, to another format which is lossy, will result in loss of information as the compression algorithms will always discard data from the source data. However, because this operation is being performed across formats with high bit rates, the loss will be fairly limited. For more information, see [this Wikipedia article on generation loss](http://en.wikipedia.org/wiki/Generation_loss). |
1,084,194 | I'm working on a page using `<canvas>`, which is a HTML5 tag, in Visual Web Developer Express Edition 2008, and the validator in the HTML editor is telling me it's an invalid tag. That's because it's set to validate against XHTML 1.0 Transitional. I'd prefer for it to not do that and tell me what's valid or invalid based on the HTML5 doctype, but I can't find anywhere in the preferences that suggests this would be possible.
Is there a way to tell Visual Studio to validate against HTML5, or add a new spec reference manually? I'd prefer not to have to go in and add tags manually, which appears to be the only option at the moment. | 2009/07/05 | [
"https://Stackoverflow.com/questions/1084194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16308/"
] | I created a validation schema that you're free to use:
<http://johndyer.name/post/2009/07/21/HTML5-XHTML5-Validation-Schema-for-Visual-Studio-2008.aspx> | This is now included in [Visual Studio 2010 SP1](http://www.microsoft.com/download/en/details.aspx?id=23691) |
52,223,462 | To help learn about machine learning I am coding up some examples, not to show that one method is better than another, but to illustrate how to use various functions and what parameters to tune. I started with [this blog](https://www.r-craft.org/r-news/boost-series-i-advantage-in-smooth-functions/) that compared BooST and xgboost, then I successfully added gbm to the example. Now I am trying to add glmnet, but the model returned alwyas has (near) zero for both of the coefficients. Either I am doing something wrong, or glmnet is just not the correct algo for this data. I am trying to figure out which it is. Here is my reproducible example:
```
# Uncomment the following 2 lines if you need to install BooST (requires devtools)
#library(devtools)
#install_github("gabrielrvsc/BooST")
library(BooST)
library(xgboost)
library(gbm)
library(glmnet)
# Data generating process
dgp = function(N, r2){
X = matrix(rnorm(N*2,0,1),N,2)
X[,ncol(X)] = base::sample(c(0,1),N,replace=TRUE)
aux = X
yaux = cos(pi*(rowSums(X)))
vyaux = var(yaux)
ve = vyaux*(1-r2)/r2
e = rnorm(N,0,sqrt(ve))
y = yaux+e
return(list(y = y, X = X))
}
# Real data
x1r = rep(seq(-4,4,length.out = 1000), 2)
x2r = c(rep(0,1000), rep(1,1000))
yr = cos(pi*(x1r+x2r))
real_function = data.frame(x1 = x1r, x2 = as.factor(x2r), y = yr)
# Train data (noisy)
set.seed(1)
data = dgp(N = 1000, r2 = 0.5)
y = data$y
x = data$X
# Test data (noisy)
set.seed(2)
dataout=dgp(N = 1000, r2 = 0.5)
yout = dataout$y
xout = dataout$X
# Set seed and train all 4 models
set.seed(1)
BooST_Model = BooST(x, y, v = 0.18, M = 300 , display = TRUE)
xgboost_Model = xgboost(x, label = y, nrounds = 300, params = list(eta = 0.14, max_depth = 2))
gbm_Model = gbm.fit(x, y, distribution = "gaussian", n.trees = 10000, shrinkage = .001, interaction.depth=5)
glmnet_Model = cv.glmnet(x, y, family = "gaussian", alpha=0)
coef(glmnet_Model)
```
>
> coef(glmnet\_Model)
>
>
> 3 x 1 sparse Matrix of class "dgCMatrix"
> 1
>
>
> (Intercept) 0.078072154632597062784427066617354284971952438
>
>
> V1 -0.000000000000000000000000000000000000003033534
>
>
> V2 -0.000000000000000000000000000000000000044661342
>
>
>
```
# Predict from test data
p_BooST = predict(BooST_Model, xout)
p_xgboost = predict(xgboost_Model, xout)
p_gbm = predict(gbm_Model, xout, n.trees=10000)
p_glmnet = predict(glmnet_Model, xout)
# Show RMSE
sqrt(mean((p_BooST - yout)^2))
sqrt(mean((p_xgboost - yout)^2))
sqrt(mean((p_gbm - yout)^2))
sqrt(mean((p_glmnet - yout)^2))
fitted = data.frame(x1 = x[,1], x2 = as.factor(x[,2]),
BooST = fitted(BooST_Model),
xgboost = predict(xgboost_Model, x),
gbm = predict(object = gbm_Model, newdata = x, n.trees = 10000),
glmnet = predict(glmnet_Model, newx = x, s=glmnet_Model$lambda.min)[, 1], y = y)
# Plot noisy Y
ggplot() + geom_point(data = fitted, aes(x = x1, y = y, color = x2)) + geom_line(data = real_function, aes(x = x1, y = y, linetype = x2))
# Plot xgboost
ggplot() + geom_point(data = fitted, aes(x = x1, y = y), color = "gray") + geom_point(data = fitted, aes(x = x1, y = xgboost, color = x2)) + geom_line(data = real_function, aes(x = x1, y = y, linetype = x2))
# Plot BooST
ggplot() + geom_point(data = fitted, aes(x = x1, y = y), color = "gray") + geom_point(data = fitted, aes(x = x1, y = BooST, color = x2)) + geom_line(data = real_function, aes(x = x1, y = y, linetype = x2))
# Plot gbm
ggplot() + geom_point(data = fitted, aes(x = x1, y = y), color = "gray") + geom_point(data = fitted, aes(x = x1, y = gbm, color = x2)) + geom_line(data = real_function, aes(x = x1, y = y, linetype = x2))
# Plot glmnet
ggplot() + geom_point(data = fitted, aes(x = x1, y = y), color = "gray") + geom_point(data = fitted, aes(x = x1, y = glmnet, color = x2)) + geom_line(data = real_function, aes(x = x1, y = y, linetype = x2))
``` | 2018/09/07 | [
"https://Stackoverflow.com/questions/52223462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7351478/"
] | ```
String joined = Arrays.stream(myArray)
.mapToObj(String::valueOf)
.collect(Collectors.joining(""));
System.out.println(joined);
``` | I will go old school, which works every time no matter what as follows:
```
String myString = "";
for(int val : myArray)
{
myString += val;
}
System.out.println(myString); // To check the output of myString
```
Will work! Hope this helps!
**Note**: This will work in Embedded Java as well where StringBuilder and some other classes are stripped for embedded devices. |
1,475,059 | I have a few that I think are correct. These are background colours for messages.
* ERROR: red;
* INFO: blue;
* SUCCESS: green;
* NOT IMPORTANT INFO: yellow
Have I got the blue and yellow around the wrong way? Any hex values that are a de facto standard for these?
I am curious considering web development, but I think the answers will be agnostic.
Here is an interesting thought (I'm sure I've read about it in an article). What colours would the errors be on [Target's website](http://www.target.com/), considering all their branding is red? | 2009/09/25 | [
"https://Stackoverflow.com/questions/1475059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31671/"
] | There are no standards for hex values to use. In most cases you will want to consider the choice in the context of the site or application. Try a range and you'll find one that sticks.
Colour can mean different things in different countries so you may want to consider alternatives if you need to support users in a country like China. | Yellow usually means warning. Less important info might be gray text without any special icon or background color.
But ultimately it needs to make sense to your users. |
21,325,661 | How do you convert an image from a path on the user's computer to a base64 string in C#?
For example, I have the path to the image (in the format `C:/image/1.gif`) and would like to have a data URI like `data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD..` representing the `1.gif` image returned. | 2014/01/24 | [
"https://Stackoverflow.com/questions/21325661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2398275/"
] | Try this
```
using (Image image = Image.FromFile(Path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
``` | You can use `Server.Map` path to give relative path and then you can either create image using `base64` conversion or you can just add `base64` string to `image src`.
```
byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/Upload_Image.png"));
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
``` |
907,674 | I'm receiving from socket A and writing that to socket B on the fly (like a proxy server might). I would like to inspect and possibly modify data passing through. My question is how to handle border cases, ie where the regular expression I'm searching for would match between two successive socket A read and socket B write iterations.
```
char buffer[4096]
int socket_A, socket_B
/* Setting up the connection goes here */
for(;;) {
recv(socket_A, buffer, 4096, 0);
/* Inspect, and possibly modify buffer */
send(socket_B, buffer, 4096, 0);
/* Oops, the matches I was looking for were at the end of buffer,
* and will be at the beginning of buffer next iteration :( */
}
``` | 2009/05/25 | [
"https://Stackoverflow.com/questions/907674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In that sense you're talking about (and all senses for, say, TCP) sockets are streams. It follows from your question that you have some structure in the data. So you must do something similar to the following:
1. Buffer (hold) incoming data until a boundary is reached. The boundary might be end-of-line, end-of-record, or any other way that you know that your regex will match.
2. When a "record" is ready, process it and place the results in an output buffer.
3. Write anything accumulated in the output buffer.
That handles most cases. If you have one of the rare cases where there's really no "record" then you have to build some sort of state machine (DFA). By this I mean you must be able to accumulate data until either a) it can't possibly match your regex, or b) it's a completed match.
**EDIT:**
If you're matching fixed strings instead of a true regex then you should be able to use the [Boyer-Moore](http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm) algorithm, which can actually run in sub-linear time (by skipping characters). If you do it right, as you move over the input you can throw previously seen data to the output buffer as you go, decreasing latency and increasing throughput significantly. | One alternative is to use `poll(2)`-like strategy with non-blocking sockets. On read event grab a buffer from the socket, push it onto incoming queue, call the lexer/parser/matcher that assembles the buffers into a stream, then pushes chunks onto the output queue. On write event, take a chunk from the output queue, if any, and write it into the socket. This sounds kind of complicated, but it's not really once you get used to the inverted control model. |
12,428,185 | I'm working on a project of type "ASP.NET dynamic data LINQ to LINQ application".
When i execute my application I'm getting all labels and DropDownLists dynamically binding.
I'm referring [this](http://www.shubho.net/2011/03/customizing-dynamic-data-application.html) blog.
Now I need to populate those DropDownList based on my criteria. Currently, it is populating all the records which is there in table for that column. How can I customize this DropDownList like I want to select only User with `Mak` name?
I guess i need to made some linq query here when dropdown populated values? not sure
```
protected void Page_Load(object sender, EventArgs e)
{
if (DropDownList1.Items.Count == 0)
{
if (Mode == DataBoundControlMode.Insert || !Column.IsRequired)
{
DropDownList1.Items.Add(new ListItem("[Not Set]", ""));
}
PopulateListControl(DropDownList1);
}
SetUpValidator(RequiredFieldValidator1);
SetUpValidator(DynamicValidator1);
}
```
 | 2012/09/14 | [
"https://Stackoverflow.com/questions/12428185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428073/"
] | In order to customize data in `DropDownList` control in Dynamic Data site you should use `FilterUIHintAttribute` class (in your metadata) that allows to replace (or add new filters) default (`built-in filters templates`) filters.
Consider example of implementing new filter template **using built-in filter template** for columns of `Boolean` type (as in the attached picture).
Let's suppose that you have table `WorkFlows` with column `Status` of `Boolean` type (`bit` for SQL Server) and you would like that `DropDownList` control has only `false` value (by default user can choose filter value from *All, True, False,*
and *[Not Set]* if the column allows null values).
First of all copy built-in filter template `Boolean.ascx` (you can find it in `~\DynamicData\Filters` directory) and then paste one to the same directory. Then rename new filter to `StatusBoolean.ascx`.
Then you can edit code-behind of `StatusBoolean.ascx` and delete line with
```
DropDownList1.Items.Add(new ListItem("True", Boolean.TrueString));
```
Then you should change metadata for `WorkFlows` entity:
```
[FilterUIHint("StatusBoolean")]
public bool Status { get; set; }
```
That's all.
More information at [FilterUIHintAttribute Class](http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.filteruihintattribute.aspx).
You can also look my post at [ASP.NET Dynamic Data automatically populating a Drop Down list based on Metadata](https://stackoverflow.com/questions/16146497/asp-net-dynamic-data-automatically-populating-a-drop-down-list-based-on-metadata/16211566). | I'm assuming that the data type you are binding is a nullable bool (bool?). When assigning the DataSource property, you can use `myObjects.Where( o => o.TheNullableBool.HasValue )`. |
9,469,537 | Do I need to worry about performance in the case below and save the result of the expensive call, or does the compiler recognise it can do the expensive call once?
```
String name;
if (object.expensiveCall() != null) {
name = object.expensiveCall().getName();
}
``` | 2012/02/27 | [
"https://Stackoverflow.com/questions/9469537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/534994/"
] | You're looking for something called [memoization](http://en.wikipedia.org/wiki/Memoization). [This question](https://stackoverflow.com/questions/3934777/java-automatic-memoization) suggests that Java can't do it natively.
In general, memoization is only possible if the compiler/JIT can prove that the function has no side-effects. So I wouldn't count on it.
But is it really that hard to just save the result?
```
String name;
ObjectType temp = object.expensiveCall();
if (temp != null) {
name = temp.getName();
}
``` | How could the Java compiler know, that `expensiveCall` has no side effects? In the general case - it cannot. Also: You might recompile the class of `object` anytime without recompiling your current class. And what would happen if `expensiveCall` has got side effects *now*? No way for automatic optimization.
BTW: The JIT-Compiler at *runtime* might have more information. But *expensive* calls are usually not considered for inlining and hence also not to further optimization steps. |
9,071,205 | I'm going to make a word wrap algorithm in PHP. I want to split small chunks of text (short phrases) in *n* lines of maximum *m* characters (*n* is not given, so there will be as much lines as needed). The peculiarity is that lines length (in characters) has to be much balanced as possible across lines.
Example of input text:
```none
How to do things
```
Wrong output (this is the normal word-wrap behavior), *m=6*:
```none
How to
do
things
```
Desired output, always *m=6*:
```none
How
to do
things
```
Does anyone have suggestions or guidelines on how to implement this function? Basically, **I'm searching something for pretty print short phrases on two or three** (as much as possible) **equal length lines**.
---
**Update**: It seems I'm searching exactly for a [**Minimum raggedness word wrap algorithm**](http://en.wikipedia.org/wiki/Word_wrap#Minimum_raggedness). But I can't find any implementation in a real programming language (anyone, then I can convert it in PHP).
---
**Update 2**: I started a bounty for this. Is it possible that do not exist any public implementation of Minimum raggedness algorithm in any procedural language? I need something written in a way that can be translated into *procedural instructions*. All I can find now is just a bounch of (generic) equation that however need a optimal searching procedure. I will be grateful also for an implementation that can only approximate that optimal searching algorithm. | 2012/01/30 | [
"https://Stackoverflow.com/questions/9071205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/995958/"
] | I've implemented on the same lines of Alex, coding the Wikipedia algorithm, but directly in PHP (an interesting exercise to me). Understanding how to use the optimal cost function *f(j)*, i.e. the 'recurrence' part, is not very easy. Thanks to Alex for the well commented code.
```
/**
* minimumRaggedness
*
* @param string $input paragraph. Each word separed by 1 space.
* @param int $LineWidth the max chars per line.
* @param string $lineBreak wrapped lines separator.
*
* @return string $output the paragraph wrapped.
*/
function minimumRaggedness($input, $LineWidth, $lineBreak = "\n")
{
$words = explode(" ", $input);
$wsnum = count($words);
$wslen = array_map("strlen", $words);
$inf = 1000000; //PHP_INT_MAX;
// keep Costs
$C = array();
for ($i = 0; $i < $wsnum; ++$i)
{
$C[] = array();
for ($j = $i; $j < $wsnum; ++$j)
{
$l = 0;
for ($k = $i; $k <= $j; ++$k)
$l += $wslen[$k];
$c = $LineWidth - ($j - $i) - $l;
if ($c < 0)
$c = $inf;
else
$c = $c * $c;
$C[$i][$j] = $c;
}
}
// apply recurrence
$F = array();
$W = array();
for ($j = 0; $j < $wsnum; ++$j)
{
$F[$j] = $C[0][$j];
$W[$j] = 0;
if ($F[$j] == $inf)
{
for ($k = 0; $k < $j; ++$k)
{
$t = $F[$k] + $C[$k + 1][$j];
if ($t < $F[$j])
{
$F[$j] = $t;
$W[$j] = $k + 1;
}
}
}
}
// rebuild wrapped paragraph
$output = "";
if ($F[$wsnum - 1] < $inf)
{
$S = array();
$j = $wsnum - 1;
for ( ; ; )
{
$S[] = $j;
$S[] = $W[$j];
if ($W[$j] == 0)
break;
$j = $W[$j] - 1;
}
$pS = count($S) - 1;
do
{
$i = $S[$pS--];
$j = $S[$pS--];
for ($k = $i; $k < $j; $k++)
$output .= $words[$k] . " ";
$output .= $words[$k] . $lineBreak;
}
while ($j < $wsnum - 1);
}
else
$output = $input;
return $output;
}
```
?> | Here is a bash version:
```
#! /bin/sh
if ! [[ "$1" =~ ^[0-9]+$ ]] ; then
echo "Usage: balance <width> [ <string> ]"
echo " "
echo " if string is not passed as parameter it will be read from STDIN\n"
exit 2
elif [ $# -le 1 ] ; then
LINE=`cat`
else
LINE="$2"
fi
LINES=`echo "$LINE" | fold -s -w $1 | wc -l`
MAX=$1
MIN=0
while [ $MAX -gt $(($MIN+1)) ]
do
TRY=$(( $MAX + $MIN >> 1 ))
NUM=`echo "$LINE" | fold -s -w $TRY | wc -l`
if [ $NUM -le $LINES ] ; then
MAX=$TRY
else
MIN=$TRY
fi
done
echo "$LINE" | fold -s -w $MAX
```
example:
```
$ balance 50 "Now is the time for all good men to come to the aid of the party."
Now is the time for all good men
to come to the aid of the party.
```
Requires 'fold' and 'wc' which are usually available where bash is installed. |
8,714,090 | Is there a way to do a wildcard element name match using `querySelector` or `querySelectorAll`?
The XML document I'm trying to parse is basically a flat list of properties
* I need to find elements that have certain strings in their names.
* I see support for wildcards in attribute queries but not for the elements themselves.
Any solution except going back to using the apparently deprecated XPath (IE9 dropped it) is acceptable. | 2012/01/03 | [
"https://Stackoverflow.com/questions/8714090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1128062/"
] | Set the tagName as an explicit attribute:
```
for(var i=0,els=document.querySelectorAll('*'); i<els.length;
els[i].setAttribute('tagName',els[i++].tagName) );
```
I needed this myself, for an XML Document, with Nested Tags ending in `_Sequence`. See *JaredMcAteer* answer for more details.
```
document.querySelectorAll('[tagName$="_Sequence"]')
```
I didn't say it would be pretty :)
PS: I would recommend to use `tag_name` over tagName, so you do not run into interferences when reading 'computer generated', implicit DOM attributes. | i'm looking for **regex + not + multiClass** selector, and this is what I got.
Hope this help someone looking for same thing!
```
// contain abc class
"div[class*='abc']"
// contain exact abc class
"div[class~='abc']"
// contain exact abc & def(case-insensitively)
"div[class~='abc'][class*='DeF'i]"
// contain exact abc but not def(case-insensitively)
"div[class~='abc']:not([class*='DeF'i])"
```
css selector doc: <https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors>
simple test: <https://codepen.io/BIgiCrab/pen/BadjbZe> |
16,900,614 | I am curious, if I have two pointers
```
int *x = (int *)malloc(sizeof(int));
int *y;
```
and I want y to point to the address of x, is
```
y = x;
```
the same as
```
y = &*x;
```
? | 2013/06/03 | [
"https://Stackoverflow.com/questions/16900614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876508/"
] | Your question has two parts, and it's worth noting that they are not both correct:
First, you ask:
>
> is
>
> y = x;
>
> the same as
>
> y = &\*x;
>
>
>
Since the dereference (`*`) and address-of (`&`) operators have the same [precedence](http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence) they will bind right to left, so
```
y = &*x;
```
is the same as:
```
y = &(*x);
```
And yes, that will yield the same effect as `y=x;` Now if you have a C compliant compiler that follows the letter of the law, it will not only be the same effectively, it *will* be the same, this is due to section 6.5.3.2 P3 of the C Specification:
>
> The unary & operator yields the address of its operand. If the operand has type ‘‘type’’,
> the result has type ‘‘pointer to type’’.
>
>
> If the operand is the result of a unary \* operator,
> neither that operator nor the & operator is evaluated and the result is as if both were
> omitted
>
>
>
So the compiler will see both the `*` and `&` together and omit them entirely.
---
In the second half of your question you stated:
`I want y to point to the address of x`
Presumably you know that that's not what you're doing, but you're setting `y` to point to *the same address* as `x` instead. `x` of course has its own address and that could be set, but you'd need a different variable `int **y = &x;` assuming `x` is a valid value to be dereferenced. | Here is a handy little function that may help. Not sure that you need all of the "includes".
```
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
int main() {
int *x = (int *)malloc(sizeof(int));
int *y = x;
int *z = &*x;
//y = x;
//z = &*x;
cout << "x has type: " << typeid(x).name() << '\n'
<< "y has type: " << typeid(y).name() << '\n'
<< "z has type: " << typeid(z).name() << '\n'
<< "values are " << x <<" "<< y << " " << z << '\n';
}
```
The result I get from this is:
```
x has type: Pi
y has type: Pi
z has type: Pi
values are 0x1a3a010 0x1a3a010 0x1a3a010
```
The answer then is, Yes, the methods are exactly the same using Ubuntu 14.10, g++ |
8,889,958 | I have an array. One of the values in that array `responses[1]` is an integer. This integer can be from 1 to whatever number you want. I need to get the last number in the integer and determine based on that number if I should end the number with 'st', 'nd', 'rd', or 'th'. How do I do that? I tried:
```
var placeEnding;
var placeInt = response[1]; //101
var stringInt = placeInt.toString();
var lastInt = stringInt.charAt(stringInt.length-1);
if (lastInt == '1'){
placeEnding = 'st';
} else if (lastInt == '2'){
placeEnding = 'nd';
} else if (lastInt == '3'){
placeEnding = 'rd';
} else {
placeEnding = 'th';
}
```
but that did not work. Every time I tried printing `placeEnding` it was always 'th' no matter if it should have been 'st', 'rd', or 'nd'. When I tried printing `placeInt`, `stringInt`, or `lastInt` they all printed as `"` instead of the number. Why is this so? When I print `responses[1]` later on in the script I have no problem getting the right answer. | 2012/01/17 | [
"https://Stackoverflow.com/questions/8889958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407756/"
] | If all you want is the last digit, just use the modulus operator:
`123456 % 10 == 6`
No need to bother with string conversions or anything. | Alternate way to get lastInt is:
```
var lastInt = parseInt(stringInt)%10;
switch lastInt {
case 1:
placeEnding = 'st';
break;
case 2:
placeEnding = 'nd';
break;
case 3:
placeEnding = 'rd';
break;
default:
placeEnding = 'th';
}
``` |
5,373,107 | Is it possible to implement `static` class member functions in \*.cpp file instead of doing
it in the header file ?
Are all `static` functions always `inline`? | 2011/03/21 | [
"https://Stackoverflow.com/questions/5373107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Yes you can define static member functions in \*.cpp file. If you define it in the header, compiler will by default treat it as inline. However, it does not mean separate copies of the static member function will exist in the executable. Please follow this post to learn more about this:
[Are static member functions in c++ copied in multiple translation units?](https://stackoverflow.com/questions/5372091/are-static-member-functions-in-c-copied-in-multiple-translation-units) | @crobar, you are right that there is a dearth of multi-file examples, so I decided to share the following in the hopes that it helps others:
```
::::::::::::::
main.cpp
::::::::::::::
#include <iostream>
#include "UseSomething.h"
#include "Something.h"
int main()
{
UseSomething y;
std::cout << y.getValue() << '\n';
}
::::::::::::::
Something.h
::::::::::::::
#ifndef SOMETHING_H_
#define SOMETHING_H_
class Something
{
private:
static int s_value;
public:
static int getValue() { return s_value; } // static member function
};
#endif
::::::::::::::
Something.cpp
::::::::::::::
#include "Something.h"
int Something::s_value = 1; // initializer
::::::::::::::
UseSomething.h
::::::::::::::
#ifndef USESOMETHING_H_
#define USESOMETHING_H_
class UseSomething
{
public:
int getValue();
};
#endif
::::::::::::::
UseSomething.cpp
::::::::::::::
#include "UseSomething.h"
#include "Something.h"
int UseSomething::getValue()
{
return(Something::getValue());
}
``` |
31,614,645 | I'm starting to learn swift, but ran into an error. Ive just created a very simple app from a course I'm following, that calculates a cats ages based on what the user enters. The first version of the app just times what the user enters by 7, which i managed todo no problem. I thought I would have a play with what I've written and change it todo this:
* 1st human year = 15 cat years
* 2nd human year = +10
* 3rd human year = +4
* 4th human year = +4
* 5th human year = +4
so on..
e.g. a 4 year old cat would be 33 in cat years.
So I want my results label to say You're cat is 33 in cat years
This is the code I've written:
```
@IBAction func findAge(sender: AnyObject) {
var enteredAge = enterAge.text.toInt()
if enteredAge = 1 {
var catYears = 15
resultLabel.text = "You're cat is \(catYears) in cat years"
} else if enteredAge = 2 {
var catYears = 25
resultLabel.text = "You're cat is \(catYears) in cat years"
} else {
var catYears = (15 + 25) + (enteredAge - 2) * 4
resultLabel.text = "You're cat is \(catYears) in cat years"
}
}
@IBOutlet weak var enterAge: UITextField!
@IBOutlet weak var resultLabel: UILabel!
```
This error I'm getting is on the line 17 "if enteredAge = 1 {" it states this "cannot assign a value of type 'int' to a value of type 'int?'"
I don't really understand why this value cannot be a integer, any help would be great. | 2015/07/24 | [
"https://Stackoverflow.com/questions/31614645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3434939/"
] | You have already assigned the value to the `enteredAge` variable like follows:
```
var enteredAge = enterAge.text.toInt()
```
So, you cannot do assignment on the place of this if expression. and you need to have condition on the if expression as follows.
```
if enteredAge == 1 {
var catYears = 15
resultLabel.text = "You're cat is \(catYears) in cat years"
}
```
This may help you. | should look like this :
```
@IBAction func button(sender: AnyObject) {
var inputYears = textField.text.toInt()!
if inputYears == 1 {
var catOld = 15
result.text = "Your cat is \(catOld) years old"
}
else if inputYears == 2 {
var catOld = 25
result.text = "Your cat is \(catOld) years old"
}
else {var catOld = (15+25) + (inputYears - 2)*4
result.text = "Your cat is \(catOld) years old"
}
``` |
62,146 | The trackpad on my Macbook Pro just started acting oddly. It's randomly clicking (which might cause me to switch programs), right-clicking and even once my screen even showed the swiping animation as if I was trying to switch to a different desktop.
Part of me fears that this is some sort of joke hacking attempt (I know of a USB device you plug into someones computer and it randomly moves their mouse and types on their keyboard), but there is nothing plugged into my machine and I just turned off the Wi-Fi and watched as this web page tried to close, the mouse right clicked twice, highlighted a word and clicked "Paste and Match Style" in the Chrome right-click menu.
Also as I've been typing (with my Wi-Fi turned off) the mouse has randomly been clicking inside this question and changing where I am typing.
I just plugged in a USB mouse which seems to work fine but the trackpad is now nearly useless. I can't even move the mouse cursor more than a few centimeters with it.
Is this a common issue?
**EDIT**
I think it is dying actually. I can now click but not move at all with the trackpad, while a regular mouse works fine.
**EDIT 2**
And now it seems to be working again. I turned on the option for "Ignore Trackpad when Mouse is plugged in" under Universal Access. I cleaned the trackpad with rubbing alcohol, I whined and complained for a few minutes to my dog, turned **off** the "Ignore Trackpad" setting, unplugged the USB mouse, and the Trackpad **appears** to be working mostly normally.
If I run my finger across it at the top or bottom portion of the mouse, it works, but there is a line horizontally across it (almost exactly where a physical trackpad button would end on the old trackpads) that is "dead". The mouse stops moving, or moves sluggishly when hitting that spot and that "spot" goes across the whole trackpad. | 2012/08/27 | [
"https://apple.stackexchange.com/questions/62146",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/4049/"
] | This was fixed -- and remains fixed -- after a **third internet Reinstall**.
Done through the Recovery Partition, start up with Command R. | Shift/control/option and turn off the computer wait 10 secs and then start-up,it should stop that annoying cursor. |
14,927,085 | This is what I have:
```
public class A1tester {
static String dna = "GCTTTA";
static String dna1 = "GCTAAAAAD";
public static void main(String[] args) {
validChars(dna);
validChars(dna1);
}
private static boolean validChars(String dna) {
try {
for (char c: dna.toCharArray()) {
assert ((c == 'C') || (c == 'G') || (c == 'T') || (c == 'A'));
}
} catch (Exception e) {
System.out.println("Exception caught!");
return false;
}
System.out.println("DNA has only the permitted letters");
return true;
}
}
```
What am I missing that's preventing my validChars() method from identifying dna1 as containing other than the four permitted characters?
Thanks. | 2013/02/17 | [
"https://Stackoverflow.com/questions/14927085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1478804/"
] | `assert` throws [`AssertionError`](http://docs.oracle.com/javase/7/docs/api/java/lang/AssertionError.html) which is not a subclass of [`Exception`](http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html), but a subclass of [`Error`](http://docs.oracle.com/javase/7/docs/api/java/lang/Error.html). | Assert throws an Error, which is not an Exception!
Try this:
```
...
catch (Throwable e)
```
or to catch only the assertion failure:
```
catch (AssertionError e)
``` |
3,018,123 | **Problem:** I want to determine the original file creation time from a file uploaded to my server via PHP.
My understanding is that the file is copied from the client to a temporary file on my server, which then is referenced in the $\_FILES var. The temporary file is of course of no use because it was just created. Is there any way I could get the creation date from the clients original file?
Thanks | 2010/06/10 | [
"https://Stackoverflow.com/questions/3018123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/324801/"
] | That data is not sent by the browser, so there's no way to access it. The data sent along with the file is `mime-type`, `filename` and file contents.
If you want the creation date, you'll either need the user to provide it or create a special file uploading mechanism via Flash or Java. | No, the stream of data is written to a file in the tmp dir instead of the file being simple 'copied' to your webserver, to it's technically a 'new' file. |
535,596 | What is your biggest pet peeve related to the windbg debugger from microsoft?
(note: I actually really like windbg if I ignore the unpolished UI.) | 2009/02/11 | [
"https://Stackoverflow.com/questions/535596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5429/"
] | Attempting to dock a window is almost always the wrong kind of dock the first time until :I move the mouse just right. Why can't it have the docking cues that VS2008 has? | Key presses are ignored while the focus is in a source window. It's not like you can edit the source code from inside windbg. At least there's the Alt-1 workaround. |
2,047,793 | What is the difference between override and overload? | 2010/01/12 | [
"https://Stackoverflow.com/questions/2047793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190623/"
] | * Overloading: picking a method **signature** at compile time based on the number and type of the arguments specified
* Overriding: picking a method **implementation** at execution time based on the actual type of the target object (as opposed to the compile-time type of the expression)
For example:
```
class Base
{
void foo(int x)
{
System.out.println("Base.foo(int)");
}
void foo(double d)
{
System.out.println("Base.foo(double)");
}
}
class Child extends Base
{
@Override void foo (int x)
{
System.out.println("Child.foo(int)");
}
}
...
Base b = new Child();
b.foo(10); // Prints Child.foo(int)
b.foo(5.0); // Prints Base.foo(double)
```
Both calls are examples of *overloading*. There are two methods called `foo`, and the compiler determines which signature to call.
The first call is an example of *overriding*. The compiler picks the signature "foo(int)" but then at execution time, the type of the target object determines that the implementation to use should be the one in `Child`. | On interesting thing to mention:
```
public static doSomething(Collection<?> c) {
// do something
}
public static doSomething(ArrayList<?> l) {
// do something
}
public static void main(String[] args) {
Collection<String> c = new ArrayList<String> ();
doSomething(c); // which method get's called?
}
```
One would suppose the method with the ArrayList argument would be called but it doesn't. The first method is called since the proper method is selected at compile time. |
1,517,718 | Does every infinite field contain a *countably infinite* subfield?
It's easy to see that every field $K$ contains either the rational numbers $\Bbb Q$ (when $K$ has characteristic $0$) or a finite field $\Bbb F\_p$ (when $K$ has characteristic $p$). Thus, in the characteristic $0$ case, the answer is an easy "yes."
But if $K$ is infinite and has characteristic $p>0$, does the fact that $K \supset \Bbb F\_p$ allow us to conclude that $K$ has a countably infinite subfield? | 2015/11/07 | [
"https://math.stackexchange.com/questions/1517718",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/80762/"
] | Yes. If $S$ is a countably infinite subset of $K$ then the subfield generated by $S$ is countable.
Since the question got six upvotes before any answers, maybe this is not obvious. Details:
Let $S\_0=S$. Let $S\_{n+1}$ consist of the elements of $S\_n$ together with all the $x+y$, $x-y$, $xy$ and $x^{-1}$ for $x,y\in S\_n$. Then $\bigcup\_{n=0}^\infty S\_n$ is a countable subfield.
(Yes, the same argument shows that $K$ has a subfield of any infinite cardinality less than or equal to the cardinality of $K$.) | Suppose $K$ has characteristic $p$.
If $K$ has a transcendental element $\alpha$, then $\mathbf{F}\_p(\alpha) \subseteq K$ is countably infinite, being isomorphic to the rational function field $\mathbf{F}\_p(x)$.
Otherwise, $K \subseteq \overline{\mathbf{F}}\_p$ which is countable, so you can just take $K$ itself to be the countably infinite subfield. |
20,479,527 | I have a parent class `Parent` and a child class `Child`. `Parent` has a method `doSomething` which is extended by `Child` (it calls `[super doSomething]` before doing its own stuff).
Under certain circumstances the parent checks some details and knows that nothing more should happen so returns. I expected a return statement in the parent implementation to prevent the child's implementation from continuing, but it seems that is not the case. The child implementation continues. Is that diagnosis correct?
If so, how can I achieve what I am looking for?
In my real application, the parent is doing a lot of work to check whether or not it should return, code which I would prefer not to duplicate in each of its multiple children. | 2013/12/09 | [
"https://Stackoverflow.com/questions/20479527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/225253/"
] | One way would be to change `doSomething` to have a return value of `BOOL`. If the method completes fully, return `YES`, otherwise return `NO`. Then you can do something like:
Parent:
```
- (BOOL)doSomething {
// lots of processing
if (/* can't finish for some reason */) {
return NO;
} else {
return YES;
}
```
Child:
```
- (BOOL)doSomething {
BOOL res = [super doSomething];
if (res) {
// complete child processing
}
return res;
}
``` | One additional solution I am considering is to split the 'test' and the 'action' as follows. `Parent`'s `doSomething` will perform the test. If necessary, it will return. Otherwise, it will call `doThisOtherThing`. `doThisOtherThing` in the parent will be empty.
Each `Child` *will* implement `doThisOtherThing`. It will not have a redefinition of `doSomething`. |
13,410,497 | In this case, my xml file shows a certain layout while at runtime another one is generated. I am incredibly confused as to why the layout shown at runtime is completely different from the one given. here is the code for the xml file
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
<Button
android:id="@+id/signUp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sign up!" />
</LinearLayout>
```
This displays Insert name here on both a label and button. The button is correctly bound and pressing it does do something, however I cannot type in the textfield at runtime. | 2012/11/16 | [
"https://Stackoverflow.com/questions/13410497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1515921/"
] | This one looks fine. Double check if you are changing any property with your java code. | Try to use this one instead. I have removed the useless LinearLayout and try to make the EditText clickable.
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/signUp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sign up!" />
</LinearLayout>
``` |
48,919,416 | I have two Forms (Form "Sales Order" and Form "Insert Detail Document"). In Form "Sales Order" I have insert some values into several objects, please refer to the following screenshot:
[](https://i.stack.imgur.com/IHiOK.jpg)
After insert some values for header document, next I want to insert detail document by clicked on Add button in Form "Sales Order".
Form "Insert Detail Document" will be shown after that button was clicked, please refer to the following screenshot:
[](https://i.stack.imgur.com/cEmB0.jpg)
I have insert all values in all objects in "Insert Detail Document". I need all values in this Form will be shown in Data Grid View in Form "Sales Order" by clicking on Add button this Form. So, Form will be shown like the following screenshot:
[](https://i.stack.imgur.com/k5LuU.jpg)
Does anyone knows how to provide this condition ?
Thanks. | 2018/02/22 | [
"https://Stackoverflow.com/questions/48919416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5014709/"
] | ```
public class Product_List {
public string Branch { get; set; }
public string InvetoryID { get; set; }
public string Warehouse { get; set; }
public string Quantity { get; set; }
public string Unit { get; set; }
}
public partial class Insert_Detail : Form
{
public DataTable Grid_Product = new DataTable();
List<Product_List> productlist = new List<Product_List>();
private void Add_Click(object sender, EventArgs e)
{
pcmn.cmn_DT.Clear();
Grid_Product.Clear();
productlist.Add(new Product_List
{
Branch = txt_Branch.Text,
InvetoryID = ddlInvetoryID.SelectedValue.ToString(),
Warehouse = ddlWarehouse.SelectedValue.ToString(),
Quantity = txt_Quantity.Text,
Unit = txt_Unit.Text,
});
Grid_Product = ToDataTable(productlist);
this.Close();
}
}
public partial class SalesOrder : Form
{
public void AddItem_Click(object sender, EventArgs e)
{
POS_ITEM_Details popup = new POS_ITEM_Details();
popup.ShowDialog();
foreach (DataRow row in popup.Grid_Product.Rows)
{
SalesOrder_Grid.Rows.Add(row["Branch"].ToString(), row["InvetoryID"].ToString(),row["Warehouse"].ToString(),..);
}
}
public DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
``` | In such cases i prefer to use an event.
You could register the events in your main form.
On the add button, you could inform the grid window.
You could transport your data in some easy to use EventArgs.
This way allows you to easily change your form by just expand your EventArgs |
10,117,258 | I'm querying a table in a db using php. one of the fields is a column called "rank" and has data like the following:
```
none
1-bronze
2-silver
3-gold
...
10-ambassador
11-president
```
I want to be able to sort the results based on that "rank" column. any results where the field is "none" get excluded, so those don't factor in. As you can already guess, right now the results are coming back like this:
```
1-bronze
10-ambassador
11-president
2-silver
3-gold
```
Of course, I would like for it to be sorted so it is like the following:
```
1-bronze
2-silver
3-gold
...
10-ambassador
11-president
```
Right now the query is being returned as an object. I've tried different sort options like natsort, sort, array\_multisort but haven't got it to work the way I'm sure it can. I would prefer keeping the results in an object form if possible. I'm passing the data on to a view in the next step. although, it's perfectly acceptable to pass the object to the view and then do the work there. so it's not an issue after all. :)
thank you for your help. i'm hoping I'm making sense. | 2012/04/12 | [
"https://Stackoverflow.com/questions/10117258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/196230/"
] | preamble is a source code comment appearing before the function that documents its behaviour, normally in a way that a tool like doxygen can automatically create useful documentation from it.
A good policy for documentation is to **document everything that isn't obvious and nothing that is**. On that basis, I'd say your getXXX() have no pre- or post-conditions worth documenting. Something like "must be called on a properly constructed object" is just a waste of the reader's time, as is a post-condition like "the caller will have received a copy of the student-specific XXX data". Don't do it! The question of whether the values can legally be empty strings is one for the constructor (or may even be a class invariant - something the class maintains as true, for instance by having the constructor throw if a value is empty and by not providing functions that wipe out the values), not for the `get` function documentation.
Similarly, your comments for firstName, lastName and major add absolutely no value, but your comment for `uid` does add value - documenting a requirement for a string format! From that I can tell you've made a mistake, as the field is an `int`, and there's something to investigate and correct. But more generally, say you had a string type - a comment might usefully communicate some restrictions on the format of the id, say that these ids relate to some other API or source, give an example etc.
More generally, pre-conditions aren't only for mutator (data changing) functions. For example, a function `day_for_date(int year, int month, int day)` that tells you what day of the week a particular date falls on may have a pre-condition that year/month/day does actually describe say a valid date between 1000 and 3000 A.D.. That's nasty, but it means if you've already checked that somewhere the function call doesn't waste time re-verifying it. In Defensive Programming style (which IMHO tends to make for more robust code) you would tend not to make that a precondition; instead, accept redundant verification as a net win (though you may provide explicit options to disable it if the caller needs the performance), and document an exception or error outcome should the date not meet expectations. The difference is that a precondition is something the caller must guarantee for the function to operate as documented, where-as in defensive programming you generally let the caller try something and have a defined/documented manageable behaviour - a change in state, return value or error reported in a predictable way - for as broad a range of prior states and inputs as is practical.
Post-conditions only make sense for mutators: whatever could be asserted about the state after the call to a non-mutating accessor must have been true beforehand - it might be a class invariant. | If this is homework, I **strongly** suggest you ask this question in class as most teachers have some particular requirements that an online community is unlikely to know about (unless you tell us ;-). That being said, we might be able to get you started in the right direction.
The *preamble* is usually a (short) description of what a particular file, class or function does.
The *pre-conditions* are the requirements on the arguments passed by the caller, as well as the program state prior to the call. They establish under what conditions the function will produce the correct results. For instance, you may request that the first and last names in your example class constructor are non-empty.
A *post-condition* usually documents side-effects applied by a function. For instance,
```
class Person
{
public:
std::string firstName () const;
// post-condition: firstName() returns 'name'.
void setFirstName (std::string name);
};
```
The wikipedia articles on [pre-conditions](http://en.wikipedia.org/wiki/Precondition) and [post-conditions](http://en.wikipedia.org/wiki/Postcondition) provide more elaborate descriptions. |
108,484 | As a PhD student in a multidisciplinary subject, I am grouped with a postdoc by my supervisor. In our lab, the usual rule is student do the theory and coding, and postdoc do the experiment.
My collaborator postdoc is highly unmotivated: he badly performed the experimental tasks that I told him to do (most of the time, the experiments was unqualified), and delayed our project progress.
I am much younger than him, and he refused to follow my instructions, and instead fed me with unreliable “ideas” and asked me to do his job... My supervisor knows the situation, but does nothing and just watches. Each weekly meeting I am the only guy having progress.
At end I had to do the experimental part myself. It was tough but finally the project was accepted to a top journal. I have done 95%+ works, but have to add the postdoc as a coauthor (he didn’t even take part in writing the paper)
I anticipate similar course of action in future projects. I can’t change the group.
How can I properly motivate my postdoc to get him work for me?
**Edits**:
The question has been revived and let me summarize some of comments. It helps to clarify some statements:
* "get him work for me" simply means "do his duty as a collaborator".
* The postdoc received authorship; but I am actually the guy doing all the works.
* The whole story is, I gave up pushing on him, did the bio training myself, and finished the data acquisition myself.
* In this question I am humbly asking how to avoid similar situations from happening again.
* I am not being harsh from the very first beginning. I was polite to the postdoc, even after wasting months.
* Technician is not a negative word. If you are familar with bio labs, you will know most postdocs are no more than a "technician", most of them cannot get a decent faculty position (e.g. top 100 US universities). I am a technician too, but just in coding. The only scientist is the professor. | 2018/04/21 | [
"https://academia.stackexchange.com/questions/108484",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/33520/"
] | To motivate someone, or at least not demotivate them, you should make them feel valued and taken seriously. Everything you are saying points in the direction of that not happening.
For example, your postdoc isn't working *for* you; he is working *with* you. Or at least, that's how the situation should be if you want him to be motivated. You are also saying he has to follow your instructions, and do experiments you tell him to do. You describe him as a technician. If I were the experimentator in such a collaboration I'd be very unwilling to put in any effort.
Obviously, making someone feel valued and taken seriously will not turn them into a better experimentator. So in some collaborations being respectful towards your collaborator will be very effective, and in some collaborations it won't be. But the way I see it, you have nothing to lose. | As a postdoc who is often unmotivated, I will try to help you out.
Clearly you are not in ideal academic ambiance for high-quality intellectual output. Your supervisor looks parasitic in relying on others to work on their own albeit in his behalf, and this postdoc is relying on you to do the hard work. Providing the worst quality results for a demanding mate is the oldest recipe for not being asked to do anything. (Like breaking some expensive piece when pushed to wash the dishes).
In that case you're stuck and I don't see anyway around it. However parasites have a lot to lose, in fact more than their host.
I suggest you be bold and do the unexpected: tell your postdoc and boss you're fed up and leaving. My guess is that they'll make concessions to keep you. Do not expect them to change this game: you will just get something this time, for a while. In any case, should you leave anyway, I don't think you will be doing a bad business.
In most cases dropping a bad PhD is way better that swallowing it whole, and still much better than not having had the experience. Reconsider this logic if you must return funding/salary (see your contract conditions).
Shake these mites off you and get on with your life. |
1,143,335 | I'm designing a .net interface for sending and receiving a HL7 message and noticed on this forum theres a few people with this experience.
My question is.... Would anyone be able to share their experience on **how long** it could take to get a message response back from a hospital HL7 server. (Particularly when requesting patient demographics) - seconds / minutes / Hours?
My dilemma is do I design my application to make the user wait for the message to come back.
(Sorry if this is a little off topic, it’s still kinda programming related? – I searched the web for HL7 forums but got stuck so again if anyone knows of any please let me know )
cheers,
Jason | 2009/07/17 | [
"https://Stackoverflow.com/questions/1143335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/138234/"
] | This is quite dependent on the kind of HL7 message sent, typically messages like ADT's are sent as essentially updates to the server, and are acknowledged almost immediately if the hospital system is behaving well. This will result in a protocol level acknowledgement, which indicates that the peer has received the message but not necessarily processed it yet.
Typically, most systems will employ a broker or message queue in their integration engines so you get your ack almost immediately.
Other messages like lab request messages *may* actually send another non-ack message back which contains the information requested. These requests can take longer.
You can check with the peer you're communicating with to see what integration engine they are using, and if a queue sits on that end which would help ensure the response times are short.
In the HL7 integration tool I work on, we use queues for inbound data so we can responde immediately. And for our outbound connections, 10s timeouts are default, and seem to work fine for most of our customers. | It depends if the response is generated automatically by a system or if the response is generated after an user does something on the system. For an automatic response it might take less than a second, depending of course on the processing that is done by the system and the current work load of that system. If the system is not too busy and processing is just a couple of queries and verification of some conditions, considering network delays, response time should be a few seconds or less. |
323,840 | I updated my MacBook Pro 13" to Lion a few weeks ago. I just found out that Apache Bench (apache2.2.19) is not working. It always shows this error, no matter what:
>
> apr\_socket\_recv: Connection reset by peer (54)
>
>
>
I also did a clean install on my Mac Mini and it produced the same error.
How can I fix this? | 2011/08/16 | [
"https://superuser.com/questions/323840",
"https://superuser.com",
"https://superuser.com/users/94354/"
] | This is due to a bug in the Apache software that's bundled with Lion. A more recent version of Apache (beta) fixes the problem. To fix ab, here are the steps:
1. Download the latest version of Apache
```
$ wget http://apache.mirrors.pair.com//httpd/httpd-2.3.16-beta.tar.bz2
```
If 2.3.16 is not available, go to <http://apache.mirrors.pair.com/httpd> and get the latest
2. Install pcre (you need brew for this)
```
$ brew install pcre
```
3. Build Apache
```
$ tar xzvf httpd-2.3.16-beta.tar.bz2
$ cd httpd-2.3.16-beta
$ ./configure
$ make
```
4. Overwrite the existing ab with the newly built one
```
$ sudo cp support/ab /usr/sbin
``` | Using the method of updating ab through homebrew at [this](http://simon.heimlicher.com/articles/2012/07/08/fix-apache-bench-ab-on-os-x-lion) link worked for me.
```
brew install 'https://raw.github.com/simonair/homebrew-dupes/e5177ef4fc82ae5246842e5a544124722c9e975b/ab.rb'
brew test ab
``` |
16,543,078 | What is the fastest way in Python to replace sequence of 3 and more same characters in utf-8 text?I need to replace sequence of 3 and more same characters with exact 2 characters.
I.e.
```
aaa -> aa
bbbb -> bb
abbbcd -> abbcd
124xyyyz3 -> 124xyyz3
``` | 2013/05/14 | [
"https://Stackoverflow.com/questions/16543078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2000535/"
] | ```
>>> import re
>>> re.sub(r'(\w)\1{2,}', r'\1\1', 'aaa')
'aa'
>>> re.sub(r'(\w)\1{2,}', r'\1\1', 'bbbb')
'bb'
``` | You can use regular expression:
```
import re
re.sub(r'(.)\1{2,}', r'\1\1', 'bbbbbaaacc')
```
Pattern captures any character followed by the same character repeated two or more times and matches this substring. The replacement replaces a matched substring with just two of the captured character. Dot will not replace repeated new lines, use `(.|\n)` or `re.DOTALL` flag for that.
It works with Unicode too:
```
re.sub(r'(.)\1{2,}', r'\1\1', u'жжж')
```
And if you have a string variable `x` containing utf-8 text, use `x.decode('utf-8')`. |
3,047,010 | The official Redis homepage lists JDBC-Redis and JRedis. What are the advantages / disadvantages of each ? Are there any other options ? | 2010/06/15 | [
"https://Stackoverflow.com/questions/3047010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7111/"
] | just an update: it seems jredis is not that active anymore, jedis however is going strong and had some great features implemented recently, it s also the same developer of JOhm.
extract from their readme on github:
Ok.. so what can I do with Jedis?
[...]
Transactions
Pipelining
Publish/Subscribe
Persistence
control commands
Remote server control commands
Connection pooling
Sharding (MD5, MurmureHash)
Key-tags for sharding
Sharding with pipelining
I was using jredis until recently on half a dozen of projects, moved them all to jedis in no time, without surprises. | JDBC-Redis is just a JDBC wrapper for JRedis database.
If you plan on using your code with different back-ends then JDBC is a good way to go. NOTE: It is not a complete JDBC implementation and the NOSQL will bleed through.
If you are going to stay with Redis then I would suggest using the API, which will give you more flexibility. Use a DAO layer pattern to encapsulate your DB Access and down the road that is all you will need to change. |
4,173,787 | I have a string in which the word `local` occurs many times. I used the `find()` function to search for this word, but it will also find e.g. `locally`. How can I match `local` exactly? | 2010/11/13 | [
"https://Stackoverflow.com/questions/4173787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1648247/"
] | ```
line1 = "This guy is local"
line2 = "He lives locally"
if "local" in line1.split():
print "Local in line1"
if "local" in line2.split():
print "Local in line2"
```
Only line1 will match. | If you want to check for existence, try to think the other way...
and you can make something like this...
check for a pattern not equal to what you want exactly and if there's a match
then check if the result is equal to what you want.
```
st1:str ='local!'
st2:str =' locally!'
match1 = re.search(r'local\w?',st1)
match2 = re.search(r'local\w?',st2)
print('yes' if match1 and match1.group()=='local' else 'no')
print('yes' if match2 and match2.group()=='local' else 'no')
``` |
66,050,982 | This is a noob question but how come when I assign 'john.residence?.numberOfRooms = 5' and then attempt to unwrap the value with optional-chaining, it prints "no rooms"??
I would think by assigning (numberOfRooms = 5) that it would contain that value???
```
class Residence {
var numberOfRooms = 1
}
class Person {
var residence: Residence?
}
let john = Person()
john.residence?.numberOfRooms = 5 // I try to assign the value 5
if let roomCount = john.residence?.numberOfRooms {
print("\(roomCount)") // why is roomCount not 5???
} else {
print("no rooms")
}
// -> no rooms
``` | 2021/02/04 | [
"https://Stackoverflow.com/questions/66050982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Have you added few lines of configuration on AndroidManifest.xml ?
You should add:
```
<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:screenOrientation="portrait"
android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>
```
check this url: <https://pub.dev/packages/image_cropper/versions/1.3.1>
and section: How to install | Any Feedback on this?
It seems it happening every time i call pickImage.
Future getImage() async {
final \_imageFiles =
await ImagePicker().getImage(source: ImageSource.gallery);
```
if (_imageFiles != null) {
File _imageFile = await Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => ImageCropper(file: File(_imageFiles.path))),
);
if (_imageFile != null) {
setState(() {
profilePicChange = _imageFile.path;
// Navigator.pop(context);
});
}
}
``` |
39,797,552 | I'm currently working my way through a "List" unit and in one of the exercises we need to create an anagram (for those who don't know; *two words are an anagram if you can rearrange the letters from one to spell the other*).
The easier solution that comes to mind is:
```
def is_anagram(a, b):
return sorted(a) == sorted(b)
print is_anagram('god', 'dog')
```
It works, but it doesn't really satisfy me. If we were in this situation for example:
```
def is_anagram(a, b):
return sorted(a) == sorted(b)
print is_anagram('god', 'dyog') #extra letter 'd' in second argument
>>> False
```
Return is False, although we should be able to to build the word `'god'` out of `'dyog'`. Perhaps this game/problem isn't called an anagram, but I've been trying to figure it out anyway.
**Technically my solution is to:**
1- Iterate through every element of b.
2- As I do, I check if that element exists in a.
3- If all of them do; then we can create a out of b.
4- Otherwise, we can't.
I just can't seem to get it to work. **For the record, I do not know how to use `lambda`**
**Some tests:**
```
print is_anagram('god', 'ddog') #should return True
print is_anagram('god', '9d8s0og') #should return True
print is_anagram('god', '_@10d_o g') #should return True
```
Thanks :) | 2016/09/30 | [
"https://Stackoverflow.com/questions/39797552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5337929/"
] | If you need to check if `a` word could be created from `b` you can do this
```
def is_anagram(a,b):
b_list = list(b)
for i_a in a:
if i_a in b_list:
b_list.remove(i_a)
else:
return False
return True
```
**UPDATE(Explanation)**
`b_list = list(b)` makes a `list` of `str` objects(characters).
```
>>> b = 'asdfqwer'
>>> b_list = list(b)
>>> b_list
['a', 's', 'd', 'f', 'q', 'w', 'e', 'r']
```
What basically is happening in the answer: We check if every character in `a` listed in `b_list`, when occurrence happens we remove that character from `b_list`(we do that to eliminate possibility of returning `True` with input `'good'`, `'god'`). So if there is no occurrence of another character of `a` in rest of `b_list` then it's not advanced anagram. | ```
def is_anagram(a, b):
test = sorted(a) == sorted(b)
testset = b in a
testset1 = a in b
if testset == True:
return True
if testset1 == True:
return True
else:
return False
```
No better than the other solution. But if you like verbose code, here's mine. |
8,772,570 | Is there a project online that I can download and study that covers unit testing (Nunit or VS)?
I'm new to unit testing and thought it could be helpful to learn by real example. | 2012/01/07 | [
"https://Stackoverflow.com/questions/8772570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194076/"
] | There are multiple samples installed with NUnit already.
See the [list of NUnit samples](http://www.nunit.org/index.php?p=samples&r=2.5.10). | Sharp Architectue's [Northwind sample project has NUnit tests](https://github.com/sharparchitecture/Northwind/tree/master/Solutions/Northwind.Tests)
[Their Who-Can-Help-Me sample project has MSpec tests](https://github.com/sharparchitecture/Northwind/tree/master/Solutions/Northwind.Tests)
There are really tons of projects out there with nunit tests, go to github, or bitbucket, or codeplex and search for "nunit".
A bit of unsolicited advice: once you get the very basics, don't bother with the visual studio MSTest. It really has some weirdness that makes it a nightmare to work with. A bit more unsolicited advice: to run non-MSTests from within visual studio [TestDriven.Net](http://www.testdriven.net/) is indispensable. |
174,278 | Is it possible (how) to mount an VHD file created by Windows 7 in OS X?
I found some information about how to do this on linux. There is a fuse fs "vdfuse" which uses virtualbox libs to mount filesystems supported by virtualbox. However I was unable to compile the package on osx because nearly all headers are missing and I doubt that it would work anyway...
**EDIT #2:** Okay I got my hands dirty and finally compiled vdfuse (<http://forums.virtualbox.org/viewtopic.php?f=26&t=33355&start=0>) on osx. As a starting point I used macfuse (<http://code.google.com/p/macfuse/>) and looked at the example file systems.
This led me to the following build script
```
infile=vdfuse.c
outfile=vdfuse
incdir="your/path/to/vbox/headers"
INSTALL_DIR="/Applications/VirtualBox.app/Contents/MacOS"
CFLAGS="-pipe"
gcc -arch i386 "${infile}" \
"${INSTALL_DIR}"/VBoxDD.dylib \
"${INSTALL_DIR}"/VBoxDDU.dylib \
"${INSTALL_DIR}"/VBoxVMM.dylib \
"${INSTALL_DIR}"/VBoxRT.dylib \
"${INSTALL_DIR}"/VBoxDD2.dylib \
"${INSTALL_DIR}"/VBoxREM.dylib \
-o "${outfile}" \
-I"${incdir}" -I"/usr/local/include/fuse" \
-Wl,-rpath,"${INSTALL_DIR}" \
-lfuse_ino64 \
-Wall ${CFLAGS}
```
You actually don't need to compile VirtualBox on your machine, just install a recent version of VirtualBox.
So now I can partially mount vhds. The separate partitions appear as block files Partition1, Partition2, ... on my mount point.
However Mac OS X does not include a loopback file system and macfuse's loopback fs does not work with block files, so we need a loopback fs to mount the blockfiles as actual partitions. | 2010/08/25 | [
"https://serverfault.com/questions/174278",
"https://serverfault.com",
"https://serverfault.com/users/52273/"
] | Finally I got it working. So in summary here are the steps to perform
1. Install macfuse
2. Install Virtual Box
3. Compile vdfuse as mentioned in the question
4. Mount the vhd disk
sudo ./vdfuse -tVHD -w -f/Path/To/VHD /Path/To/Mountpoint
5. Attach the virtual partition blockfiles
hdiutil attach -imagekey diskimage-class=CRawDiskImage -nomount /Path/To/Mountpoint/PartitionN
6. Mount the virtual partition
mount -t YourFS /dev/diskK /Path/To/ParitionMountPoint | FUSE works on MacOSX, however you would need the headers. |
72,128,276 | I essentially want recode and rename a range of variables in a dataframe. I am looking for a way to do this in the single step.
Example in pseudo-code:
```
require(dplyr)
df <- iris %>% head()
df %>% mutate(
paste0("x", 1:3) = across( # In the example I want to rename
Sepal.Length:Petal.Length, # the variables I've selected
~ .x + 1 # and recoded to "x1" ... "x5"
)
)
df
```
Desired output:
```
x1 x2 x3 Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <fct>
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
``` | 2022/05/05 | [
"https://Stackoverflow.com/questions/72128276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9434803/"
] | Maybe `rename_with()` is what you want. After that you can manipulate these renamed columns with `mutate(across(...))`.
```r
library(dplyr)
df %>%
rename_with(~ paste0("x", seq_along(.x)), Sepal.Length:Petal.Length) %>%
mutate(across(x1:x3, ~ .x * 10))
x1 x2 x3 Petal.Width Species
1 51 35 14 0.2 setosa
2 49 30 14 0.2 setosa
3 47 32 13 0.2 setosa
4 46 31 15 0.2 setosa
5 50 36 14 0.2 setosa
6 54 39 17 0.4 setosa
```
---
If you want to manipulate and rename a range of columns in one step, try the argument `.names` in `across()`.
```r
df %>%
mutate(across(Sepal.Length:Petal.Length, ~ .x * 10,
.names = "x{seq_along(.col)}"),
.keep = "unused", .after = 1)
x1 x2 x3 Petal.Width Species
1 51 35 14 0.2 setosa
2 49 30 14 0.2 setosa
3 47 32 13 0.2 setosa
4 46 31 15 0.2 setosa
5 50 36 14 0.2 setosa
6 54 39 17 0.4 setosa
```
*Hint: You can use `seq_along()` to create a sequence 1, 2, ... along with the selected columns, or `match()` to get the positions of the selected columns in the data, i.e.
`.names = "x{match(.col, names(df))}"`.* | You could add consecutive numbers to `n` columns with the same prefix this way:
```
df <- iris %>% head()
n <- 3
colnames(df)[1:n] <- sprintf("x%s",1:n)
```
output:
```
# x1 x2 x3 Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
# 5 5.0 3.6 1.4 0.2 setosa
# 6 5.4 3.9 1.7 0.4 setosa
```
Of any nonconsecutive number of columns by:
```
n <- c(1,3,5)
colnames(df)[n] <- sprintf("x%s",n)
# x1 Sepal.Width x3 Petal.Width x5
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
# 5 5.0 3.6 1.4 0.2 setosa
# 6 5.4 3.9 1.7 0.4 setosa
``` |
28,248,496 | Since the Apple "Users & Roles" update to iTunesConnect end of november 2015 some people have been experiencing an error message "iTunes Store operation Failed" and "You are not authorized to use this service".
This happens when using XCode 6 and 7

Previously i was able to upload app using the same iTunes account. | 2015/01/31 | [
"https://Stackoverflow.com/questions/28248496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4044969/"
] | I know it is an old question, but maybe I noticed something that it might help you.
Today when I try to login to **Itunes Connect** via browser, Apple returns me a message "*Your Apple ID or password was entered incorrectly.*" , but I'm sure that my id and pass was correct . It seems apple side problem, not ours.
I think that there is something that it doesn't work in Apple, and it is **not** an Xcode bug.
I don't know why they don't warn anyone about that.
**EDIT**
Now *Apple* updated its [System Status - Apple Developer](https://developer.apple.com/system-status/). | Delete your Apple ID from xocde and add it again, make sure you quite beta Xcode if you have opened, then open it again, clean, archive, validate, it works for me |
30,798,794 | I am writing a WPF application which uses a number of unmanaged DLL's. Something in the program is causing memory leak and I monitored the application using Redgate ANTS 8 Memory Profiler. ANTS shows that the memory usage of MSVCR110.dll is constantly increasing.
The question is that can managed code cause this leak by using MSVCR110.dll?
If not can I find which of the unmanaged dll's is using MSVCR110.dll and causing leak?
(My program has reference to MSVCR110.dll directly.) | 2015/06/12 | [
"https://Stackoverflow.com/questions/30798794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3670437/"
] | Take a few Snapshots and see if there is any growth in any managed objects. You can select objects with source options in ANTS memory profiler and if instance count it growing for any of your objects. And then, you can have a look at the ‘Instance Retention graph’ for any of growing instance and see which holds the reference.
And also, make sure you unsubscribe from any subscription you make to the third party components and call dispose and set null pointers appropriately. | The answer was not easy to find. I had tried each DLL that I suspected one by one. The leak was an undeleted array in a C++/CLI wrapper class. Since it is a managed dll, I think, the native "new" calls are traced through msvcr110.dll, and ANTS shows leak in that dll. |
76,245 | Throughout *Logan* we see that Charles does not have the same control of his powers as he did in previous movies.
He has these seizures that keeps everyone paralyzed and harms people. He talks to himself (people that don't exist?!).
We also see that Wolverine does not have the same healing efficiency, his claws do not work as well as before.
**Is this because of his aging? Does every mutant that ages start losing control of his/her powers?** | 2017/07/13 | [
"https://movies.stackexchange.com/questions/76245",
"https://movies.stackexchange.com",
"https://movies.stackexchange.com/users/42976/"
] | There are a couple of ways to interpret the series of events and how each mutant has lost their powers.
**1. They're both getting old.**
At the time of Logan, Xavier is about 97 years old. Logan's physical body is reaching about 150 years old (although depending on the timeline shenanigans he could mentally be a lot older). Logan hasn't been kind to his body, relying on it's healing ability heavily throughout his life. We don't know the science, but it could easily be that since he's gotten older his powers have weakened, either due to old age or the extensive use of his power. Add on top of that the adamantium in his body poisoning him, and you've got a Wolverine that can't heal as well.
Charles, at his age, is suffering from seizures, and seems to be suffering from [Alzheimer's and dementia](https://en.wikipedia.org/wiki/Alzheimer%27s_disease) as well. At the time of the movie the mix of old age and mutant powers is unknown, but with Charles having a psychic ability it wouldn't be surprising if the two are hand in hand, IE his ability causing his illness
**2. They're slowly being killed by the chemicals in the food**
Both Charles and Logan, along with their friend, are relatively alone in the world. It has been years since a new mutant has born, and previous events have killed off most other mutants though either mutant hunting or mass die-off events, such as Charles' seizure accident.
It was stated later in the movie that naturally born mutants stopped because of a chemical introduced into the food supply. Since this chemical somehow suppresses the mutant gene, it wouldn't be surprising for it to have an adverse, if not long term, effect on those still living. We don't know the chemical or how it works, or what it's long term effect is on those that are mutants that are living. | He wasn't. At least not specifically his powers. He was having seizures and losing control *period*. Just like if you had a seizure and your legs lashed out. |
9,204,706 | I have simple node js http server.
```
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
```
If I run
```
node basicserver.js
```
I get
```
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: listen EADDRINUSE
at errnoException (net.js:642:11)
at Array.0 (net.js:743:26)
at EventEmitter._tickCallback (node.js:192:40)
```
I have seen [this](https://stackoverflow.com/questions/8673775/process-nexttick-error-in-node-js) post, but that post seems to be specific to TCP server and not http server. Could anyone please help. | 2012/02/09 | [
"https://Stackoverflow.com/questions/9204706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/929701/"
] | The port you are listening to is already being listened by another process. In this case I got a feeling that it is your self. You can do a `ps aux | grep node` and then using `kill <pid>` kill your node process. Beside that you can also try another port.
--Update--
In case if you want to find which process is listening, you can use `netstat -lpn` ( `-l` is to find out the listening ports, `-p` is to include the process name and pid, `-n` is to not to resolve host names, or else it will be slow), to find the processes that are listening on different ports. If there was too many, you can do `netstat -lnp | grep :8888`.
Also can use, `fuser 8888/tcp`, which will show you the process pid and also adding `-k` will kill the process, fastest way ever.
I realized this two commands only work in **linux**. | The port you are listening to is already being listened by another process.
When I faced to this error I killed the process using Windows PowerShell (because I used Windows)
1. open the windows powershell
2. type `ps` and then you can get list of processes
3. find the process named `node`, and note the `Id`
4. type `Stop-process <Id>`
I think that it is help for windows users. |
7,820,809 | Why does this work:
```
a = np.random.rand(10, 20)
x_range = np.arange(10)
y_range = np.arange(20)
a_tmp = a[x_range<5,:]
b = a_tmp[:, np.in1d(y_range, [3,4,8])]
```
and this does not:
```
a = np.random.rand(10,20)
x_range = np.arange(10)
y_range = np.arange(20)
b = a[x_range<5, np.in1d(y_range,[3,4,8])]
``` | 2011/10/19 | [
"https://Stackoverflow.com/questions/7820809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235617/"
] | The Numpy reference documentation's [page on indexing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#boolean) contains the answers, but requires a bit of careful reading.
The answer here is that indexing with booleans is equivalent to indexing with integer arrays obtained by first transforming the boolean arrays with `np.nonzero`. Therefore, with boolean arrays `m1`, `m2`
```
a[m1, m2] == a[m1.nonzero(), m2.nonzero()]
```
which (when it succeeds, i.e., `m1.nonzero().shape == m2.nonzero().shape`) is equivalent to:
```
[a[i, i] for i in range(a.shape[0]) if m1[i] and m2[i]]
```
I'm not sure why it was designed to work like this --- usually, this is *not* what you'd want.
To get the more intuitive result, you can instead do
```
a[np.ix_(m1, m2)]
```
which produces a result equivalent to
```
[[a[i,j] for j in range(a.shape[1]) if m2[j]] for i in range(a.shape[0]) if m1[i]]
``` | Another way to achieve this is to select the per-axis indices you want separately, i.e.:
```py
A[rows, :][:, cols]
```
Concrete example:
```py
>>> A = np.arange(9).reshape(3, 3)
>>> A
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
# Slicing works as expected.
>>> A[1:, :2]
array([[3, 4],
[6, 7]])
# Indices that represent slice.
>>> cols = [0, 1]
>>> rows = [1, 2]
# Per OP, counterintuitively different.
>>> A[rows, cols]
array([3, 7])
# Workaround: Select axes separately.
>>> A[rows, :][:, cols]
array([[3, 4],
[6, 7]])
```
(silly code to produce above text: [link](https://github.com/EricCousineau-TRI/repro/blob/ab05f38/python/numpy/logical_indexing_2d_counterintuitive.py)) |
684,506 | I recently tried installing surfshark-vpn and openvpn3 using the following guides.
<https://surfshark.com/blog/how-to-set-up-a-vpn-on-linux>
<https://openvpn.net/cloud-docs/openvpn-3-client-for-linux/> (I feel like something in this guide might be the problem)
But since then, `apt` and `apt-get` fail giving the following message:
```
Hit:1 http://apt.pop-os.org/proprietary groovy InRelease
Ign:2 http://us.archive.ubuntu.com/ubuntu groovy InRelease
Ign:3 http://us.archive.ubuntu.com/ubuntu groovy-security InRelease
Hit:4 http://ppa.launchpad.net/system76/pop/ubuntu groovy InRelease
Ign:5 http://us.archive.ubuntu.com/ubuntu groovy-updates InRelease
Ign:6 http://us.archive.ubuntu.com/ubuntu groovy-backports InRelease
Err:7 http://us.archive.ubuntu.com/ubuntu groovy Release
404 Not Found [IP: 91.189.91.39 80]
Err:8 http://us.archive.ubuntu.com/ubuntu groovy-security Release
404 Not Found [IP: 91.189.91.39 80]
Err:9 http://us.archive.ubuntu.com/ubuntu groovy-updates Release
404 Not Found [IP: 91.189.91.39 80]
Err:10 http://us.archive.ubuntu.com/ubuntu groovy-backports Release
404 Not Found [IP: 91.189.91.39 80]
Reading package lists... Done
E: The repository 'http://us.archive.ubuntu.com/ubuntu groovy Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: The repository 'http://us.archive.ubuntu.com/ubuntu groovy-security Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: The repository 'http://us.archive.ubuntu.com/ubuntu groovy-updates Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: The repository 'http://us.archive.ubuntu.com/ubuntu groovy-backports Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
```
I've tried searching on how I can fix this but everything I've found doesn't seem to help. The most common answers seem to be:
* Run `sudo add-apt-repository -r ppa:something here` But I don't what what to put after `ppa:`
* Run `ppa-purge` but I don't have that program and I can't install it since apt and apt-get don't work.
* Delete a line in `/etc/apt/sources.list` but it looks like everything in that file is already commented out. (Will show it's contents below)
Does anyone have any suggestions for me? I'm considering just backing up my files and reinstalling but I'd much rather prefer to learn how to fix this.
I am currently using Pop!OS v20.10
This is my `sources.list` file
```
## See sources.list(5) for more information, especialy
# Remember that you can only use http, ftp or file URIs
# CDROMs are managed through the apt-cdrom tool.
# deb cdrom:[Pop_OS 20.10 _Groovy Gorilla_ - Release amd64 (20210225)]/ groovy main restricted
# deb cdrom:[Pop_OS 20.10 _Groovy Gorilla_ - Release amd64 (20210225)]/ stable main restricted
# deb cdrom:[Pop_OS 20.10 _Groovy Gorilla_ - Release amd64 (20210225)]/ unstable main restricted
```
Thanks | 2021/12/31 | [
"https://unix.stackexchange.com/questions/684506",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/508218/"
] | I'm not familiar with pop-os. Meaning I have no idea where exactly the ubuntu repositories are selected, but I think from /etc/apt/sources.list like ubuntu.
[ubuntu wiki](https://help.ubuntu.com/community/EOLUpgrades/)
the sources from code `#EOL upgrade sources.list` you can use also to install the software. For groovy
```
deb http://old-releases.ubuntu.com/ubuntu/ groovy main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ groovy-updates main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ groovy-security main restricted universe multiverse
# Optional
deb http://old-releases.ubuntu.com/ubuntu/ groovy-backports main restricted universe multiverse
``` | It isn't `apt` and `apt-get` that are failing. The error messages are due to `apt update` and/or `apt-get update`. You should still be able to install `ppa-purge` with `apt install ppa-purge`.
>
> Delete a line in /etc/apt/sources.list but it looks like everything in that file is already commented out. (Will show it's contents below)
>
>
>
Go to `/etc/apt/sources.list.d`. This directory contains the repositories you have manually added which seem to be causing the issue during updates. Comment out unnecessary lines from the problem-causing files or delete the entire files. |
65,847,773 | I have a dataframe with the following values. I want to dedect dates, when the Low is crossing below the SMA8Low.
```
df['SMA10High'] = df.loc[:,'High'].rolling(window=10).mean()
df['SMA8Low'] = df.loc[:,'Low'].rolling(window=8).mean()
df['yesterday'] = df['Low'].shift(1) >= df['SMA8Low'].shift(1) #yesterdays
LOW >= SMA8Low
df['today'] = df['Low'] <= df['SMA8Low'] #Todays Low <= SMA8Low
df.dropna(inplace=True) #droping NaN values
```
Dataframe result after the above code is the following:
[](https://i.stack.imgur.com/eBfwe.jpg)
Now the new column crossing should only be True, if yesterday is true and today is true.
I tried the following code:
```
df['crossover'] = np.where(df['yesterday'] == df['today'],True,False)
#df['crossover'] = np.where(df['today'] & (df['yesterday'] ==
df['today']),True,True)
```
[](https://i.stack.imgur.com/QG3uA.jpg)
But the result is wrong. Only the following dates should be True in the column crossover:
2021-01-08 and 2021-01-22 | 2021/01/22 | [
"https://Stackoverflow.com/questions/65847773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9107254/"
] | The "official" answer is `freopen()`. Theoretically you can call
```
freopen("somefile", "r", stdin);
```
and now `stdin` is reading from `"somefile"`. However, once you've done this it's either tricky or impossible to get `stdin` pointing back at standard input (or, as you called it, "the console") when you're done. See also questions [12.33](http://c-faq.com/stdio/freopen.html) and [12.34](http://c-faq.com/stdio/undofreopen.html) in the old [C FAQ list](http://c-faq.com/).
But really: why are you trying to reassign `stdin` in this way? `stdin` is basically a global variable, and any time you have the pattern
```
change global variable;
make function call that implicitly uses global variable;
set global variable back to what it was;
```
you have poor design and a recipe for disaster. Usually what you want to do is to create a modified version of that function call in the middle -- whatever it is -- that lets you pass the something in *as an explicit parameter*, rather than implicitly using the global variable.
In this case, you don't even need to invent anything new, because instead of `getchar()` which implicitly reads from the global `stdin`, you can just call `getc(fp)`, which reads from whatever file pointer you want to specify:
```
for (int x; x < 10; x++)
{
c = getc(fp);
}
``` | Save it in another variable first.
```
FILE *save_stdin = stdin;
stdin = fp;
...
stdin = save_stdin;
```
Of course, there may be no need to change `stdin` in the first case. You could just use `getc(fp)` instead of `getchar()`. Reassigning `stdin` would only be necessary if you're calling code that uses `stdin` and can't be changed. |
114,424 | There are a ton of questions on Programmers.SE about whether or not taking extended time off is a good idea and what to do during that time off to maintain your skill level:
<https://softwareengineering.stackexchange.com/questions/31536/will-taking-two-years-off-for-school-in-a-related-field-destroy-a-mid-level-devel>
<https://softwareengineering.stackexchange.com/questions/102009/can-i-take-a-year-off-without-hurting-my-career>
[If you take a year or two out from being a developer, is it really that hard to get back into it?](https://softwareengineering.stackexchange.com/questions/27091/if-you-take-a-year-or-two-out-from-being-a-developer-is-it-really-that-hard-to-g)
<https://softwareengineering.stackexchange.com/questions/91176/is-taking-a-break-in-career-to-learn-stuff-a-bad-idea>
They've been really helpful, but I still have a question about the logistical details of take a self-funded sabbatical.
I'm coming to the end of a year off from working as a software developer (after 7 years in the field.) I've taken this year to let myself explore interests that I'd never had enough time for: baking, sewing, photography, and making new and interesting friends. During this time, I've also been working on pet development projects in technologies and disciplines that I would never have had the chance to explore otherwise. in addition, I've read all of those software development books I'd never had time to read and kept up with programming news and blogs.
The development projects have all had an eye towards being part of a Micro ISV, but only one of the projects has made it to any sort of production stage. That project is impressive, but not very successful (yet!)
I've got a reasonably active programming blog that I believe reflects a high dedication to software development and demonstrates that I haven't just put my programming skills on a shelf for a year.
My question is: **What is the best way to transmit this information to a potential employer at the resume/cover letter level?**
I'm reasonably confident that I can explain this sabbatical in an interview setting. I know that at the resume level though, hiring managers will use any excuse they can to throw my resume out (I've done hiring and I would probably have thrown out my own resume if it didn't handle this time off really well, maybe it's karma.) So I feel like the resume/cover letter is the really tricky part in getting a kick-ass new job.
I have a few ideas about what to do, but I'm not sure what the larger community sees as acceptable. Here are the approaches I'm considering:
1. Put a special section on my resume for the sabbatical time in which I outline the personal projects. If I do this, what's a good way to label it?
2. Create a personal company name and put these projects in the work
experience section of my resume under that company. This seems like the most go-getter
way to do it, but I'm worried it could be perceived as trickery when
I get to the interview stage. Also if I do this, what do I put as my
title?
3. Leave my resume as-is and explain everything in my cover letter,
with a link to my active blog.
4. There's probably something I'm not thinking of, I'm open to any
other ideas.
I know I've included a bunch of special-snowflake information about my personal situation, but I would prefer answers for the more general case. The personal details are here more as an example than as a request for answers designed specifically for me. | 2011/10/14 | [
"https://softwareengineering.stackexchange.com/questions/114424",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/38677/"
] | Honestly I think you're over thinking it a bit. If you were gaining relevant experience during your time off, then your resume should not even show a break in your work timeline. Instead of a company name just put something like **Entrepreneurial Pursuits**.
You don't even have to explain in detail each project. The important parts are the technologies you worked on and the business problems you helped overcome. In the end, majority of hiring managers are just playing a game of buzz word search anyways. | I'm on a sabbatical myself right now so maybe we can share notes. I'm going to start by agreeing with other answers that you're thinking too much.
First step is to **have a plan** and if you have a favorite recruiter or linkedin/monster/dice etc... accounts announce your plan and time off. Even if your plan is to surf all the California beaches or pub crawl Islay, you're doing something and not just loafing around and that's all anyone cares about. No one likes the surprise of you just disappearing for a year, many will want to hear your stories when you come back.
I would recommend doing personal projects, even if small it helps to keep the physical act of coding fresh and practiced plus it gives you a little something to show. Contribute to an open sourced project as an alternative, same reasons.
I update the recruiters I work with occasionally. When I reenter the coding workforce there won't be any surprises. I agree with other answers that this needs to be on your resume. On my resume it's going down as "sabbatical" with relevant projects and accomplishments listed.
So no, I don't think that taking extended time off is a bad thing and I think that breaking out of the intensely focused environment of software development can actually be a good thing.
You don't have to "explain" the sabbatical, you will want to describe what you did and what you learned during your time off. It's a great chance to show how your diverse experiences can add to any team, your wide interests can lead to creative solutions, and now that personal time is over how you really **want** to work at where you're applying and not there just because you need a job. |
35,570,040 | I have a question about how to define a method from a subclass or a parent class. For example:
```
public class Thought
{
//-----------------------------------------------------------------
// Prints a message.
//-----------------------------------------------------------------
public void message()
{
System.out.println ("I feel like I'm diagonally parked in a " +
"parallel universe.");
System.out.println();
}
}
```
And the child class is:
```
public class Advice extends Thought
{
//-----------------------------------------------------------------
// Prints a message. This method overrides the parent's version.
//-----------------------------------------------------------------
public void message()
{
System.out.println ("Warning: Dates in calendar are closer " +
"than they appear.");
System.out.println();
super.message(); // explicitly invokes the parent's version
}
}
```
If I wanted to invoke method message from the main method, would I have to use `Thought.message`, or `Advice.message` since I used the super invoker. Does super.(method)() technically just copy and paste the parent method into the child method, allowing you to create an object of only the child? | 2016/02/23 | [
"https://Stackoverflow.com/questions/35570040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5673084/"
] | I think you need to go back and study OO a bit more...
Yes you can create an object just of the child, but it still `isA` instance of the parent too.
`super.method()` calls the superclass method. It does not copy the superclass method into the subclass.
The superclass implementation of a method might use private variables in that the subclass doesn't have access to. | ```
Thought t1 = new Thought();
t1.message(); // invokes Thought#message()
Thought t2 = new Advice();
t2.message(); // invokes Advice#message()
Advice a1 = new Advice();
a1.message(); // invokes Advice#message()
Advice a1 = new Thought(); //COMPILATION ERROR
```
As you are calling *instance methods*, at runtime whatever the object you have in the reference will be executed. |
42 | We've all had them, managers who have either come from sales or last looked at code 10 or more years ago but think they know how to write code.
What can I do to give the impression that I'm grateful for their intervention, but keep it as short as possible so I can get on with my work?
Or, should I be engaging more with the manager to educate them with modern coding techniques and practices? After all, a manager who understands these will be able to talk sensibly to clients and more senior management when discussing the project and its timescales. | 2010/09/01 | [
"https://softwareengineering.stackexchange.com/questions/42",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/47/"
] | It can be very difficult, especially if the manager thinks they're a l33t h@x0r but hasn't coded anything in the last 10 years.
Start by using [active listening](http://en.wikipedia.org/wiki/Active_listening). Make sure you understand exactly what point they're trying to get across. Rephrase it and shoot it back to them so that they know you understood them. Sometimes this is all they really care about.
If they insist on some implementation, ask yourself why you're refusing them. There has to be a reason. It probably breaks some fundamental software design principle... usually separation of concerns. Know your principles, and *know why they're better than the alternative*. Then quote the principles and explain why they should be followed in this case. That makes the discussion academic.
If you can't figure out why you don't like what they're saying, it's a good opportunity to question your assumptions. | **The problem here is that your manager obviously feels COMPETENT, when he IS NOT.**
I've had such experience before and for me it worked if I subtly showed the guy that programming wasn't his domain.
For example, I might go at great lengths to explain a specific piece of code, descending all the way into talking about hash tables and linked lists, big O notation etc., until his face shows that he really feels unable to follow any more of your discussion.
So if you can pull this off you will most likely get rid of the silly questions and micromanagement. |
12,385,109 | >
> **Possible Duplicate:**
>
> [C# Not Disposing controls like I told it to](https://stackoverflow.com/questions/1493309/c-sharp-not-disposing-controls-like-i-told-it-to)
>
>
>
I use this to delete all Pictureboxes I created on my Winform
```
foreach (PictureBox pb in this.Controls)
{
pb.Dispose();
}
```
but each time only about the half of all Pictureboxes get disposed,
the other half remains untouched
i solved it by surrounding it with a `while (Controls.OfType<PictureBox>().Count() > 0 )` Loop
so it just gets executed until all Pictureboxes are gone,
but this is a bad solution and i want to know why this happens and how i can solve it the right way | 2012/09/12 | [
"https://Stackoverflow.com/questions/12385109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1278704/"
] | [`Control.Dispose`](http://msdn.microsoft.com/en-us/library/3cc9y48w) is removing the control from the collection, changing the index and messing up the foreach.
You can solve this problem by using a reverse for loop or by creating a separate array holding the references.
**Solution #0**
```
for (int i = Controls.Count - 1; i >= 0; i--)
{
Controls[i].Dispose();
}
```
**Solution #1**
```
foreach (var control in Controls.Cast<Control>().ToArray())
{
control.Dispose();
}
``` | Try With:
```
foreach(Control c in this.Controls)
{
if(c is PictureBox)
{
c.Dispose();
this.Controls.Remove(c);
}
}
``` |
3,729,674 | Can anybody explain me, what is use of vector class? My Professor mentioned about below sentence in the lecture.
Template: Each vector has a class parameter that determines which object type will be used by that instance, usually called T. I don't understand what exactly class parameters means? | 2010/09/16 | [
"https://Stackoverflow.com/questions/3729674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/448456/"
] | The vector is defined as a template like:
```
template<typename T>
class Vector;
```
To use it you need to instantiate the template like:
```
Vector<char> myVector;
```
Instantiating a vector effectively creates a new class. which is equivalent to what you would get if you'd replaced every occurrence of T in the definition of the template with the class argument (in this case char)
So if we had a simple template
```
template<typename T>
class DataHolder{
public:
T data
}
```
Instantiated like:
```
DataHolder<char> myChar;
```
Is equivalent to the class:
```
class DataHolder
{
public:
char data;
}
``` | these two videos give very good explaination about stl and its containers iterators usages.
<http://channel9.msdn.com/shows/Going+Deep/C9-Lectures-Introduction-to-STL-with-Stephan-T-Lavavej/>
<http://channel9.msdn.com/shows/Going+Deep/C9-Lectures-Stephan-T-Lavavej-Standard-Template-Library-STL-2-of-n/> |
1,039,138 | I have a hidden input element that I am using as a counter to use to name more input elements generated by JavaScript. To get the value of the counter i use
```
parseInt($('#counter').val());
```
However I use this code snippet several times in my code, so I thought it would be good to put it in a function
```
function getCounter(){
parseInt($('#counter').val());
}
```
this always returns undefined, while running just the code snippet returns the correct value. This happens in several ways that I tried defeining the function, as a function inside a $(function(){}), as a global function etc. How do I fix the scoping? | 2009/06/24 | [
"https://Stackoverflow.com/questions/1039138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98917/"
] | Add "return" to your return statement :)
```
function getCounter(){
return parseInt($('#counter').val());
}
``` | How about adding a return
```
function getCounter(){
return parseInt($('#counter').val());
}
``` |
54,035,722 | I have this class with only the foreign key references:
```
public class Device
{
[Required]
[DataMember(Name = "key")]
[Key]
public Guid Key { get; set; }
[ForeignKey("DeviceType")]
[IgnoreDataMember]
public virtual DeviceType DeviceType { get; set; }
[ForeignKey("Model")]
[IgnoreDataMember]
public virtual ModelType Model { get; set; }
}
```
I get an error while running the command
```
Add-Migration -Name "DeviceMigration"
```
Error is:
>
> The property or navigation 'DeviceType' cannot be added to the entity type 'Device' because a property or navigation with the same name already exists on entity type 'Device'.
>
>
>
This is my context class content
```
public class MyContext: DbContext
{
public MyContext(DbContextOptions<MyContext> options)
: base(options)
{ }
public DbSet<DeviceType> DeviceTypes { get; set; }
public DbSet<Device> Devices { get; set; }
}
``` | 2019/01/04 | [
"https://Stackoverflow.com/questions/54035722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1407094/"
] | For my situation, I misused ForeignKey attribute:
```
[IgnoreMap]
public long? PLCalculationMasterId { get; set; }
[ForeignKey("PLCalculationMaster"), IgnoreMap, IgnoreDataMember]
public PLCalculationMaster PLCalculationMaster{ get; set; }
```
whereas it should have been:
```
[IgnoreMap]
public long? PLCalculationMasterId { get; set; }
[ForeignKey("PLCalculationMasterId"), IgnoreMap, IgnoreDataMember]
public PLCalculationMaster PLCalculationMaster{ get; set; }
``` | If all solutions provided above fails, just delete the migrations folder and recreate the migrations.
This error may arise due to visual studio cache references.
One could alternatively rename the property on the target entity. |
37,551,193 | When I try to transfer the form data to PHP file with this code:
**index.html** (the form):
```html
<!DOCTYPE html>
<html>
<body>
<form action="welcome.php" method="post">
First name:<br>
<input type="text" name="fname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
```
and the **welcome.php** is:
```html
<!DOCTYPE html>
<html>
<body>
Welcome <?php echo $_POST["fname"]; ?><br>
Your email address is: <?php echo $_POST["lname"]; ?>
</body>
</html>
```
when I press on the submit button I get the "welcome.php" content back:
[](https://i.stack.imgur.com/iRXYa.png)
why? and how could I fix it ? | 2016/05/31 | [
"https://Stackoverflow.com/questions/37551193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6187810/"
] | I was facing the same error message and the thread at <https://github.com/desktop/desktop/issues/9293> got me to try the command `git config --global http.sslbackend schannel` which resolved the issue. | one of the easiest way is to unset the proxy.
**Command :** git config --global --unset http.proxy |
43,238 | 18-year-old teen here with no children, I'm asking this question here on how to better communicate with my parents.
My mental health took a massive dip during the Pandemic and I'm still working on it. It got to a point where I had a crippling internet addiction just to fill the void of being socially isolated for so long. Every time I would come to talk to them about it, I would be met with being told I have a good life and I shouldn't complain, yelled at, or told something along the lines of "do better" or "work harder" (or worse, have the conversation loop around to stuff unrelated to the topic but I usually see as an attack on my character, I.E. my anxiety about trying new foods).
I sometimes feel like I can't communicate these things with my folks in a way they understand, so how can I articulate my thoughts and feelings with them about this and not have the conversation end with so-so feelings or with me feeling more shitty but silent about it. | 2023/02/07 | [
"https://parenting.stackexchange.com/questions/43238",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/44106/"
] | Maybe your parents aren't the right people to talk with about it. Not that they don't care, but there might be better chance to get what you need from other people - friends, or a support group. I have a friend who's been in a support group of equal peers for 20 years - their purpose is to help each other navigate the waters of life. | Communication is difficult. Communicating with someone you expect know you intimately is filled with assumptions, which does not simplify the situation.
Different points of view
========================
You may experience something with someone else and come away with two different points of view, and you may with time remember things differently.
Don't Project.
--------------
Keep to *Your* experience and *Your* feelings
It is vital (in my opinion) that you "stay at home" instead of projecting or using 3rd party phrasing like "People do..." or "It is normal to...".
Use "I think..." "My feeling is..." "I experience this as..." "I experience your reaction as..." instead of stating items as absolute facts. You might see things as black and white, others may se things in greyscales (or vice versa) - be aware of this.
Know your audience
------------------
Keep your different backgrounds in mind. The wording of your question leads me to assume that your parents may be less technical. Consider parallels that make more sense for them. Speak "their language" but with your point of view.
It is my experience that communication with a focus on you, rather than the counterpart will avoid many land-mines. (For example: "I feel that you are angry." is not as provocative as "You are angry")
Set up the conversation
=======================
Expected outcome
----------------
Before you start a conversation, think about what it is you want to achieve. Decide beforehand what you actually need your parents to understand. Make it clear what you expect from them, to avoid them going off at a tangent. As has already been said, if you are looking for understanding, consider other people than your parents.
Environment
-----------
Choose the time, place and environment so it suits you. If you feel vulnerable, it is vital that you have the energy to tackle feedback.
Mediating
---------
Consider bringing someone who can mediate. Priests, student counsellors, doctors could be candidates if you don't know anyone who is not emotionally involved.
If a part of the problem is interruption, consider a speaking token - the person with the token is allowed to speak.
During the conversation
=======================
When you do talk to your parents, use short sentences, keep it clear and concise. embellishments and too many examples will muddy the issue. If you need their support and consideration, say so. Make it clear what you need from them. Ignore the internet aspect of your addiction. Addiction is addiction, no matter if it is drugs/alcohol, cutting, food or some other action you become addicted to. |
21,226,188 | I'm very new to programming. And I've been trying to get the string.count function to work.
This is what I have so far:
```
def trial ():
a = raw_input ("Enter a string:").lower()
print a
b = raw_input ("Enter a substring:").lower()
print b
print "The total character count is:" + a.count('b')
```
It's still not giving me the count number. It keeps giving me `<built-in method count of str object at 0x0181B500>`.
I figure I'm doing something wrong. I realize this might be a simple question, but I'm a beginner. I read you have to use str.count (sub[,start[,end]]) but what does the start and end mean? I read the description but I didn't really get it.
Any kind of help will be appreciated! | 2014/01/20 | [
"https://Stackoverflow.com/questions/21226188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3213742/"
] | You haven't saved your code or are otherwise using `print a.count` and not `print a.count()`. The former means that you are printing the representation of the `count` method in the string object,hence the print out:
```
<built-in method count of str object at 0x0181B500>
```
As for what the `sub,start,end` means, might I recommend [the Python documentation for string objects?](http://docs.python.org/2/library/string.html#string.count)
>
>
> ```
> string.count(s, sub[, start[, end]])
>
> ```
>
> Return the number of (non-overlapping) occurrences of substring sub in string s[start:end]. Defaults for start and end and interpretation of negative values are the same as for slices.
>
>
>
In essence, this means that:
```
"Some long text right about here".count("o",5,9)
```
Will only calculate the number of `o`s in the substring `"Some long text right about here"[5:9]` which is equivilent to `"long"`, so will return `1`. | For testing purposes it's good practice to separate logic from the I/O
eg:.
```
def trial(a, b):
return "The total character count is:" + a.count('b')
```
Now you can quickly test like this
```
>>> trial("foo bar", "oo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in trial
TypeError: cannot concatenate 'str' and 'int' objects
```
Oh right, the preferred way is to use .format()
```
def trial(a, b):
return "The total character count is: {}".format(a.count('b'))
```
Now you can test it again
```
>>> trial("foo bar", "oo")
'The total character count is: 1'
```
Your original error was not generated by the code in your question. You probably had something like this
```
def trial ():
a = raw_input ("Enter a string:").lower()
print a
b = raw_input ("Enter a substring:").lower()
print b
print "The total character count is:", a.count
``` |
162,078 | I am undergoing world building for a story I am writing. In this story, the school system is level based, where there are no grades(as in grades 1-12), just accomplishments in terms of level.
--Example Clarification; Mary is nearly ending her first year of schooling:
- She has taken and passed Basic Arithmetic( +,-,\*,/ ) exams, granting a 4th year Math level
- She has taken and passed Algebraic Arithmetic exams, granting 7th year Math level
- she has also passed Precalculus exams, granting 10th year Math level
- so by her second year of schooling, she's allowed to take 11th year Calculus classes
-- however, because her parents insisted on a mathematics focus, she has yet to pass all other class's examinations:
- she has passed and taken Elementary Science granting 2nd year Science level, and so she can take 2nd year science in her 2nd year
- not enough time was invested in Social Studies and she must take 1st year Social Studies in her 2nd year
So what would that system be called? It is a system where each student's accomplishments are accumulated throughout their life as a student; and ability/competence is based on the amount of knowledge a student has at any point in time. It prevents students who already know their stuff from getting held back and it allows students who struggle to catch up when they are more mature.
If it isn't clear, think in terms of an RPG: instead of ATK, DEF, SPD having different values; MATH, SCIENCE, and GYM are the names of the stats, and their values increase when a student completes a class.
"Meritocracy" is what I'm leaning towards, but perhaps there is a different term? If so, **what is the term for this system?** | 2014/04/07 | [
"https://english.stackexchange.com/questions/162078",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/71280/"
] | Testing of students is often divided into two major categories of measurement - **normative** and **criterion based**
**Normative** measurement has to do with the comparison of pupils in a similar category. A common measure is *grade level*. Testing along these lines examines how all students in a given grade score on a testing measure. By definition, half of the children are above the middle point (median) and half are above. Students are often ranked by percentiles, that is, what percentage of students are they above (a student in the 60%ile scored above 60% of his peers). Unlike the children in [Lake Wobegon](http://en.wikipedia.org/wiki/Lake_Wobegon), all the students cannot be above average.
The second category of measurement is **criterion based**. A standard is set by educators or others who have established learning goals, and those tested are graded on how much of the material has been mastered. The median grade might be 50%, 10%, 90% or anything, even 100%.
Grading on a curve is ofen a combination of the two. The tests are initially graded based on criteria (how many answers are right) and then adjusted based on the normative pattern of the group (if the criterion scores ranged from 10% to 50% correct, it was a hard test and final grades might be adjusted upward).
In reporting test or achievement scores, it is critical to identify what type of grading is being used.
If your numbers reflect an actual mastery of a given set of material, the number of units completed is a **criterion based** measure. | I think this is just a **rating** system/schema. Lexile does the same thing for children reading levels. |
54,428,608 | I'm attempting to Dockerize a Vue.js application. I'm using the `node:10.15-alpine` Docker image as a base. The image build fails with the following error:
```
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
gyp ERR! stack at PythonFinder.failNoPython (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:484:19)
gyp ERR! stack at PythonFinder.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:406:16)
gyp ERR! stack at F (/usr/local/lib/node_modules/npm/node_modules/which/which.js:68:16)
gyp ERR! stack at E (/usr/local/lib/node_modules/npm/node_modules/which/which.js:80:29)
gyp ERR! stack at /usr/local/lib/node_modules/npm/node_modules/which/which.js:89:16
gyp ERR! stack at /usr/local/lib/node_modules/npm/node_modules/isexe/index.js:42:5
gyp ERR! stack at /usr/local/lib/node_modules/npm/node_modules/isexe/mode.js:8:5
gyp ERR! stack at FSReqWrap.oncomplete (fs.js:154:21)
gyp ERR! System Linux 4.9.125-linuxkit
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /app/node_modules/inotify
gyp ERR! node -v v10.15.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! inotify@1.4.2 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the inotify@1.4.2 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
```
The application runs on my Ubuntu machine. And I've searched for a resolution online.
I tried:
```
FROM node:10.15-alpine
EXPOSE 8080
RUN mkdir -p /app/src
WORKDIR /app
COPY build/ config/ dist/ static/ .babelrc .postcssrc.js index.html /app/
COPY package*.json ./
RUN apk add --no-cache make gcc g++ python && \
npm install --production --silent && \
apk del make gcc g++ python
ADD src/ /app/src/
CMD ["npm", "start"]
```
This fails too. The error output is quite verbose and references C/C++ code.
Here's my current Dockerfile:
```
FROM node:10.15-alpine
EXPOSE 8080
RUN mkdir -p /app/src
WORKDIR /app
COPY build/ config/ dist/ static/ .babelrc .postcssrc.js index.html /app/
COPY package*.json ./
RUN npm install
ADD src/ /app/src/
CMD ["npm", "start"]
```
Can anyone help me to resolve this issue with node-gyp? I'd like to be able to run the application from with a Docker container, but I need to get the image to build first.
### Update
Since the build was working on my Ubuntu machine, I checked the `node` version. It was 8.12, so I switch to using the `node:8.12-alpine` image and the application now works with the following Dockerfile:
```
FROM node:8.12-alpine
RUN apk add g++ make python
EXPOSE 8080
RUN mkdir /app
WORKDIR /app
COPY . /app
RUN npm install
CMD ["npm", "start"]
``` | 2019/01/29 | [
"https://Stackoverflow.com/questions/54428608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10205096/"
] | I resolve this problem by add **RUN apk add --no-cache python2 g++ make** before **npm install**
```
# Stage 1, based on Node.js, to build and compile the react app
FROM node:12-alpine as build
RUN mkdir -p /app
WORKDIR /app
COPY package*.json /app/
COPY ./ /app/
#### => add this script to resolve that problem
RUN apk add --no-cache python2 g++ make
RUN npm install \
&& npm run build
# Stage 2, based on Nginx, to have only the compiled app, ready for production with Nginx
FROM nginx:1.17-alpine
RUN mkdir -p /app
WORKDIR /app
RUN apk add --update bash jq curl \
&& rm -rf /var/cache/apk/*
COPY --from=build /app/build/ /app/build
COPY ./scripts /app/scripts
COPY .env /app/scripts/.env
COPY ./nginx.conf.template /etc/nginx/conf.d/nginx.conf.template
RUN chmod +x /app/scripts/getEnv.sh \
&& chmod +x /app/scripts/run.sh
CMD ["/bin/bash", "-c", "/app/scripts/run.sh"]
``` | I started having this problem when I went to Alpine 3.15 (I MAY have skipped 3.14; I can't remember). Instead of using a node base image, I'm using Microsoft.
It looks like in Alpine 3.13, the `npm` package was more aligned to the `nodejs` package. In Alpine 3.14, they changed `npm` to be the actual `npm` version. So, I added both `nodejs` and `npm` instead of **just** `npm` (line 2).
Here's my updated Dockerfile:
```
FROM mcr.microsoft.com/dotnet/sdk:5.0-alpine AS publish
RUN apk add --no-cache nodejs npm
WORKDIR /src
COPY . .
RUN dotnet restore "MyWeb.csproj" -r linux-musl-x64
RUN dotnet publish "MyWeb.csproj" -c Release -o /app/publish -r linux-musl-x64 --self-contained false --no-restore
FROM mcr.microsoft.com/dotnet/aspnet:5.0-alpine
WORKDIR /app
COPY --from=publish /app/publish .
ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false \
LC_ALL=en_US.UTF-8 \
LANG=en_US.UTF-8
RUN apk add --no-cache icu-libs
ENTRYPOINT ["./MyWeb"]
```
NOTE: The `npm i` occurs as part of the build in the .csproj. |
27,336,890 | I have class `Product`
```
public class Product
{
public string Name{get;set;}
public int Quantity{get;set;}
// and other
}
```
After some operation i get `List<Product>`.
How can i create string in format `productName1(productQuantity1), productName2(productQuantity2), ...` from that list?
I supposed to use `String.Join` but can't get how to use it with some dynamic object or KeyValuePair (If i use `Select` to get such objects). | 2014/12/06 | [
"https://Stackoverflow.com/questions/27336890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3625486/"
] | ```
String.Join(", ", list.Select(p => String.Format("{0}({1})", p.Name, p.Quantity)))
``` | ```
string.Join(", ", products.Select(p=>string.Format("{0}({1})",p.Name, p.Quantity)))
``` |
58,314,459 | I use docker to build a web app (a Rails app specifically).
Each build is tagged with the git SHA value and the `:latest` tag points to the latest SHA value (e.g. `4bfcf8d`) in this case.
```
# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
feeder_web 4bfcf8d c2f766746901 About a minute ago 1.61GB
feeder_web latest c2f766746901 About a minute ago 1.61GB
feeder_web c14c3e6 4cb983fbf407 13 minutes ago 1.61GB
feeder_web cc1ecd9 3923b2c0c77f 18 minutes ago 1.61GB
```
Each version only differs by some minor copy in the app's frontend, but other than that they are largely the same.
Each one is listed at 1.61GB. Does it really require an additional 1.61GB for each build if I just change a few lines in the web app? And if so, should I actively be clearing old builds? | 2019/10/10 | [
"https://Stackoverflow.com/questions/58314459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2490003/"
] | >
> Each version only differs by some minor copy in the app's frontend, but other than that they are largely the same. Each one is listed at 1.61GB. Does it really require an additional 1.61GB for each build if I just change a few lines in the web app?
>
>
>
Whether or not you can benefit from layer caching depends largely on how you write your Dockerfile.
For example if you write
```
FROM debian
COPY ./code /code
RUN apt-get update && all that jazz ... ...
...
```
and you change one iota of that `./code`, the whole layer is tossed and every layer after it. Docker has to rerun (and re-*store*) your layer, creating another few hundred meg layers every time you build. But if you run
```
FROM debian
RUN apt-get song and dance my-system deps && clean up after myself
MKDIR /code
COPY ./code/requirements /code/requirements
RUN pip or gem thingy
COPY /code/
...
```
Now you don't have to install requirements every time. So the bulk of your environment (system and language libraries) doesn't need to change. You should only need the space for whatever you copy in ./code and thereafter in this case - still usually in the 0.1 gig or so magnitude.
The community tends to tout minimization of layers in an image and as far as steps with the same lifespan and dependencies (apt-get install / cleanup ) it makes sense. But this is actually contrary to efficiency if you can make good use of caching. For example, if you need to change gem file, probably don't need to change all of system libraries, so no need to rebuild that image unless you *want* to update the lower layers. This also drastically increases build time if you don't have to install libffi-dev or whatever every time.
Likely the biggest thing you can do to keep final image sizes down is use multi stage builds. Python and Ruby containers often end up pulling in complex build time dependencies that are then kept in the final image. Removing them from the end image is also a potential security bonus, at least security overhead in terms of CVE exposure. So look up multi stage builds if you haven't yet and spend an hour seeing if it's fairly easy to get some of the build time dependencies out of your final image. Full disclosure: I cannot be sure at the moment whether these build stages are automatically cleaned up.
>
> And if so, should I actively be clearing old builds?
>
>
>
Since disk space is a fundamentally limited resource, the only question is how actively, and to what extent do you want to mitigate by increasing hard disk space.
And don't forget to clean up old containers ,too. I try to make `docker run --rm` a habit whenever possible, but still find myself pruning them after they inevitably build up. | If one build requires 1.6G then just changing a few lines is not going to change the size.
If you are not planning to use them anymore, I would suggest clearing out the old builds. Every so often I do a `docker system prune -a` which removes unused data (images, containers, volumes, etc.). |
28,415,781 | I'm coding a script for my forum which generates a preview of the given string.
Here is my js code
```
function MakePreview() {
var getText = document.getElementById('inputText').value;
document.getElementById('outputText').innerHTML = getText;}
```
Here is my HTML code
```
<article>
<h2>What are you doing?</h2>
<textarea id="inputText" onkeyup="MakePreview()"></textarea>
<br/>
<input type="submit" class="button" value="Hello"/>
</article>
<article>
<p id="outputText"></p>
</article>
```
Furthermore I have an textarea for the input and an paragraph for the output. But the output does not make a new line like textareas does.
Usually a paragraph makes automatically new lines when the string is longer than the width of the given content.
Does someone have a solution?
Thanks in advance | 2015/02/09 | [
"https://Stackoverflow.com/questions/28415781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4547314/"
] | I'm not sure, if it's possible to achieve exactly what you want (due to the different font size and family), but this snippet is very close to it.
```js
function makePreview() {
var text = document.getElementById('inputText').value;
document.getElementById('outputText').innerHTML = text;
}
```
```css
.wrapper {
width: 150px;
}
.wrapper textarea {
width: 100%;
}
#outputText {
position: relative;
white-space: pre-wrap;
word-break: break-all;
border: 1px solid #ccc;
}
```
```html
<div class="wrapper">
<textarea id="inputText" oninput="makePreview()"></textarea>
<p id="outputText"></p>
</div>
```
The idea is to wrap both the `textarea` and the `p` within a same parent to get their widths to match. `word-break: break-all` and `white-space: pre-wrap` "copies" the automatic text wrapping and entered new-lines within `textarea` to the `p` element.
However, the text might be cutted in a different place, depending on the used font family and size. You could get a better match if you'd use the same font in both elements. | In html multiple whitespaces are replaced by single space so if you want to preview in paragraph you need to replace newlines with `<br/>`
```
function MakePreview() {
var getText = document.getElementById('inputText').value;
document.getElementById('outputParagraph').innerHTML = getText.replace('\n', '<br/>');
}
``` |
147,839 | If I go to Settings --> Sound, then there's a checkmark that says "Play feedback when volume is changed." I unchecked it, but the sound effect is still there. | 2014/10/01 | [
"https://apple.stackexchange.com/questions/147839",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/21186/"
] | Use shift while changing volume. There shouldn't be any sound. | The setting for "Play feedback when volume is changed" in stored in ~/Library/Preferences/.GlobalPreferences.plist file with the key com.apple.sound.beep.feedback.
If the key value is set to 0 then feedback sound is disabled. If they key value is set to 1 then the feedback sound is enabled.
If you want to see the current value that is set you can run the following command in terminal:
defaults read ~/Library/Preferences/.GlobalPreferences.plist com.apple.sound.beep.feedback
That will output either a 0 or 1. 0 = off, 1 = on.
To set the feedback sound to disabled, run the following command in terminal:
defaults write ~/Library/Preferences/.GlobalPreferences.plist -int 0
To re enable feedback sound run the same command but replace the 0 with a 1. |
40,803,023 | I'm using the `javax.persistence` package to map my Java classes.
I have entities like these:
```
public class UserEntity extends IdEntity {
}
```
which extends a *mapped superclass* named `IdEntity`:
```
@MappedSuperclass
public class IdEntity extends VersionEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
// Getters and setters below...
}
```
The `IdEntity` super class extends another mapped super class named `VersionEntity` to make all entities inherit version properties:
```
@MappedSuperclass
public abstract class VersionEntity {
@Version
private Integer version;
// Getters and setters below...
}
```
Why?
Because now I can make generic queries on the IdEntity class for all entities, and it will look like this: (example)
```
CriteriaBuilder builder = JPA.em().getCriteriaBuilder();
CriteriaQuery<IdEntity> criteria = builder.createQuery(IdEntity.class);
```
Now to the problem.
**Some** of my entities will have timestamps like `created_at` and `deleted_at`. But **not all** entities.
I could provide these properties in my entity classes like this:
```
public class UserEntity extends IdEntity {
@Basic(optional = false)
@Column(name = "updated_at")
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;
}
```
But as I have a lot of entities, this will make me put a lot of redundant code in all entities that should have timestamps. I wish there was some way I could make the relevant classes inherit these fields in some way.
One possible solution is to create a parallell `IdEntity` superclass, maybe named `IdAndTimeStampEntity` and make those entities that should have timestamps inherit from this new superclass instead, but hey that's not fair to my colleague-developers because now they have to know which super class to choose from when writing generic queries:
```
CriteriaBuilder builder = JPA.em().getCriteriaBuilder();
CriteriaQuery<???> criteria = builder.createQuery(???); // Hmm which entity should I choose IdEntity or IdAndTimeStampEntity ?? *Annoyed*
```
And the generic entity queries become not so generic..
>
> My question: How can I make `all` of my entities inherit `id` and
> `version` fields, but only a sub part of all entities inherit
> timestamp fields, but keep my queries to a single type of entities?
>
>
>
Update #1
---------
Question from Bolzano: "can you add the code which you specify the path(holds table info) for entities ?"
Here is a working example of querying a `UserEntity` which is a `IdEntity`
```
CriteriaBuilder builder = JPA.em().getCriteriaBuilder();
CriteriaQuery<IdEntity> criteria = builder.createQuery(IdEntity.class);
Root<IdEntity> from = criteria.from(IdEntity.class);
criteria.select(from);
Path<Integer> idPath = from.get(UserEntity_.id); //generated meta model
criteria.where(builder.in(idPath).value(id));
TypedQuery<IdEntity> query = JPA.em().createQuery(criteria);
return query.getSingleResult();
``` | 2016/11/25 | [
"https://Stackoverflow.com/questions/40803023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4032222/"
] | I would pick a solution that didn't enforce a class-based object model like you've outlined. What happens when you don't need optimistic concurrency checking and no timestamps, or timestamps but no OCC, or the next semi-common piece of functionality you want to add? The permutations will become unmanageable.
I would add these common interactions as interfaces, and I would enhance your reusable find by id with generics to return the actual class you care about to the caller instead of the base superclass.
**Note: I wrote this code in Stack Overflow. It may need some tweaking to compile.**
```
@MappedSuperclass
public abstract class Persistable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
// getter/setter
}
public interface Versioned {
Integer getVersion();
}
public interface Timestamped {
Date getCreated();
Date getLastUpdated();
}
@Embeddable
public class TimestampedEntity {
@Column(name = "create_date")
@Temporal
private Date created;
@Column
@Temporal
private Date lastUpdated;
// getters/setters
}
@Entity
public class UserEntity extends Persistable implements Versioned, Timestamped {
@Version
private Integer version;
@Embedded
private TimestampedEntity timestamps;
/*
* interface-defined getters. getTimestamps() doesn't need to
* be exposed separately.
*/
}
public class <CriteriaHelperUtil> {
public <T extends Persistable> T getEntity(Class<T> clazz, Integer id, SingularAttribute idField) {
CriteriaBuilder builder = JPA.em().getCriteriaBuilder();
CriteriaQuery<T> criteria = builder.createQuery(clazz);
Root<T> from = criteria.from(clazz);
criteria.select(from);
Path<Integer> idPath = from.get(idField);
criteria.where(builder.in(idPath).value(id));
TypedQuery<T> query = JPA.em().createQuery(criteria);
return query.getSingleResult();
}
}
```
Basic Usage:
```
private UserEntity ue = CriteriaHelperUtil.getEntity(UserEntity.class, 1, UserEntity_.id);
ue.getId();
ue.getVersion();
ue.getCreated();
// FooEntity implements Persistable, Timestamped
private FooEntity fe = CriteriaHelperUtil.getEntity(FooEntity.class, 10, FooEntity_.id);
fe.getId();
fe.getCreated();
fe.getVersion(); // Compile Error!
``` | >
> I wish there was some way I could make the relevant classes inherit these fields in some way.
>
>
>
You *could* make a custom annotation `@Timed` and use an annotation processor to add the timestamp field and annotations, either by using a bytecode manipulation framework or creating a delegating subclass. Or, for example if you use Lombok, create a Lombok annotation.
That way, your team members only have to remember to use the `@Timed` annotation when you have entities with timestamps. Whether you like such approach or not is up to you. |
36,385 | I recently had reason to move a hard drive from a computer that blew up to another computer for the purpose of recovering data. Under the (unfortunate) circumstances, both the donor and the recipient were Windows XP SP3 machines. I wanted to be sure that the transplanted drive would not be altered by the recipient computer, so I searched like hell but was unable to find a way to mount the transplanted drive as read-only.
How can I mount a hard drive as read-only on Windows XP? | 2009/07/06 | [
"https://serverfault.com/questions/36385",
"https://serverfault.com",
"https://serverfault.com/users/7302/"
] | I'm answering quite late, but it might help someone else.
Everett's [solution](https://superuser.com/a/213015) on superuser explains how to modify the volume attributes to make it read-only. | I've got this bookmarked from a while back, but I've never tried it:
<http://www.microsoft.com/communities/newsgroups/list/en-us/default.aspx?dg=microsoft.public.windows.file_system&tid=4b1a14f7-6bd2-4c9f-ae64-df57c35712bf&cat=&lang=&cr=&sloc=&p=1>
The 4th post (by Edwin) has the solution I am talking about. |
8,023,323 | I have implemented a function in a singleton class with an optional parameter.
```
private function MyFunction($Name = "")
{
$localCopy = $Name;
//this check fails, EMPTY is printed!
if (empty($Name))
echo "EMPTY";
else
echo "NOT EMPTY";
//this is working, NOT EMPTY is printed
if (empty($localCopy))
echo "EMPTY";
else
echo "NOT EMPTY";
}
```
This function is called by another function in the same class.
```
public function OtherFunction($Name = '')
{
self::MyFunction($Name);
}
```
OtherFunction is called from outside
```
OtherFunction("Hello");
```
Why does the empty check only works correctly with the local copy?
Can someone explain me this?? | 2011/11/05 | [
"https://Stackoverflow.com/questions/8023323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451089/"
] | If you have a member variable which is initialized to an instance of the same class, then when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class, and when that instance is created, it will also have a member variable which is initialized to an instance of the same class...
and then the stack will overflow and it will stop. It's OK for an object to have a pointer to another instance of the same class as a member, but it's not OK to create that instance in the constructor, or have it initialized in the body of the class, or you'lll recursively create objects until your stack overflows. Normally if you want such a member variable, then you accept the object as a constructor argument. | It's a stack overflow.
It's similar to calling a function from the same function, like this:
```
void func(){
func();
}
```
It will repeat until the stack fills, and then the program will crash.
Cheers. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.