问:
How to create a database of following structure in pouchdb

I want to create a database in pouchdb that has following structure

/db

--mycontacts

------|contact1

------|contact2

------|contact3

------|contact4

Here mycontacts is a node in database db which contains all the contacts.

I want to know how I can create a node in db and push contacts in to this node as user add new contact.

答:
Using PouchDB is pretty simple:

```<code>var db = new PouchDB('mycontacts'); // Create mycontacts db

// Write contact1
db.put({
  _id: 'oscar@gmail.com',
  name: 'Oscar',
  Phone: '0987665544'
});
</code>```

EDIT:

Ultimately it's json all the way. If you want to store your contacts as an array, all you need to do is:

```<code>var db = new PouchDB('mydatabaser'); // Create mycontacts db

db.put({
  _id: '...',
  mycontacts: [{
    name: 'Oscar',
    phone: '0987665544'}, {
    name: 'Bob',
    phone: '0765432190'}, {
    name: 'Eric',
    phone: '0855664432'}
 ]
});
</code>```

A word of warning though -- the last structure is likely less efficient than the first, as every time you add a new contact you will need to mutate an existing document rather than adding a new one. Immutable structures are much better suited to the CouchDB/PouchDB/Cloudant family of databases.

Body:
Using PouchDB is pretty simple:

var db = new PouchDB('mycontacts'); // Create mycontacts db

// Write contact1
db.put({
  _id: 'oscar@gmail.com',
  name: 'Oscar',
  Phone: '0987665544'
});

EDIT:

Ultimately it's json all the way. If you want to store your contacts as an array, all you need to do is:

var db = new PouchDB('mydatabaser'); // Create mycontacts db

db.put({
  _id: '...',
  mycontacts: [{
    name: 'Oscar',
    phone: '0987665544'}, {
    name: 'Bob',
    phone: '0765432190'}, {
    name: 'Eric',
    phone: '0855664432'}
 ]
});

A word of warning though -- the last structure is likely less efficient than the first, as every time you add a new contact you will need to mutate an existing document rather than adding a new one. Immutable structures are much better suited to the CouchDB/PouchDB/Cloudant family of databases.


来源: stackexchange

问:
how to get number of product in each category with nodejs and mongodb
I'm newbie nodejs and mongodb. How can i do:

I want to get number of product in each category;

```<code>cate1(id, name) :
+ product 1(id,name,cate ,created_by)
+ product 2(id,name,cate ,created_by)
+ product 3(id,name,cate ,created_by)
+ product 4(id,name,cate ,created_by)

cate2(id, name) :
+ product 5(id,name,cate ,created_by)
+ product 6(id,name,cate ,created_by)
+ product 7(id,name,cate ,created_by)
+ product 8(id,name,cate ,created_by)
+ product 9(id,name,cate ,created_by)
</code>```

...

When i try to query in nodejs i want to get (id,name, number_of_product).

```<code>=> cate1 has 4 products
=> cate2 has 5 products
</code>```

How can i do that.

I have a query in mysql:

```<code>Select cate.id, cate.name, count(*) totalCount
from cate, product
where cate.id = 1 and product.cate = 1
</code>```

i could get :

```<code>[
    {
        id                  : 1,
        name                : cate1,
        number_of_product   : 4
    },
    {
        id                  : 2,
        name                : cate1,
        number_of_product   : 5
    },
    {
        id                  : 3,
        name                : cate2,
        number_of_product   : 2
    }
    ....
]
</code>```

Can someone translate into nodejs and mongodb.

Thanks!

答:
Hi,
I think, this is what you actually want.

```<code>Category.aggregate(
    [
      {
        $lookup: {
          from: "products",
          localField: "_id",
          foreignField: "category_id",
          as: "products"
        }
      },
      {
        $project:
        {
          _id: 1,
          category: 1,
          totalProducts: {$size: "$products"},
          products: "$products"
        }
      }
    ]
  ).exec(function(err, results) {
    if (err) {
      throw err;
    }
    res.end("" + JSON.stringify({data: results}));
  });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm newbie nodejs and mongodb. How can i do:

I want to get number of product in each category;

cate1(id, name) :
+ product 1(id,name,cate ,created_by)
+ product 2(id,name,cate ,created_by)
+ product 3(id,name,cate ,created_by)
+ product 4(id,name,cate ,created_by)

cate2(id, name) :
+ product 5(id,name,cate ,created_by)
+ product 6(id,name,cate ,created_by)
+ product 7(id,name,cate ,created_by)
+ product 8(id,name,cate ,created_by)
+ product 9(id,name,cate ,created_by)

...

When i try to query in nodejs i want to get (id,name, number_of_product).

=> cate1 has 4 products
=> cate2 has 5 products

How can i do that.

I have a query in mysql:

Select cate.id, cate.name, count(*) totalCount
from cate, product
where cate.id = 1 and product.cate = 1

i could get :

[
    {
        id                  : 1,
        name                : cate1,
        number_of_product   : 4
    },
    {
        id                  : 2,
        name                : cate1,
        number_of_product   : 5
    },
    {
        id                  : 3,
        name                : cate2,
        number_of_product   : 2
    }
    ....
]

Can someone translate into nodejs and mongodb.

Thanks!

Body:
Hi,
I think, this is what you actually want.

Category.aggregate(
    [
      {
        $lookup: {
          from: "products",
          localField: "_id",
          foreignField: "category_id",
          as: "products"
        }
      },
      {
        $project:
        {
          _id: 1,
          category: 1,
          totalProducts: {$size: "$products"},
          products: "$products"
        }
      }
    ]
  ).exec(function(err, results) {
    if (err) {
      throw err;
    }
    res.end("" + JSON.stringify({data: results}));
  });


问:
How to opimize user defined python functions handling millions of rows?
I'm using python 3.6.
My Python code is retrieving data from a database, and processing the data and saving the result in csv format. After processing, I'm getting around 80 million rows.

One field of the processed data is a value of a dictionary, and that field contains multiple value against the key; so during processing, that field's values are stored in a data frame column in list format.

I need to replace that value with the corresponding dictionary key. So I wrote the following function for converting the value to a dictionary key:

```<code>def keysWithValue(aDict, target):
    return sorted(key for key, value in aDict.items() if target == value)
</code>```

I'm feeling that if I will use a for loop for those 80 million records and call this function on each of them, it will take lots of time. Can you please suggest me some alternative Python approach instead of modifying it directly in my database that will save my code running time?

答:
The fastest you're going to get is to reverse the keys and values to create a value:key lookup map:

```<code>rev_dict = {v: k for k, v in aDict.items()}  # use aDict.iteritems() on Python 2.x
</code>```

UPDATE - if there isn't a 1-to-1 relationship between the key and the value and you have multiple values instead, you can unpack them as:

```<code>rev_dict = {i: k for k, v in aDict.items() for i in v}  # use aDict.iteritems() on Python 2.x
</code>```

Then in your code, when you retrieve the data from your DB, just grab the column value by looking through that lookup map:

```<code>column_value = rev_dict.get(column_value, column_value)
</code>```

Which will give you the key if column_value exists in aDict or will return it's own value unchanged.

Keep in mind, tho, that if your aDict isn't too big, while your approach is a bit wasteful most of the time to process those 80M rows would still be spent on I/O operations.

Body:
I'm using python 3.6.
My Python code is retrieving data from a database, and processing the data and saving the result in csv format. After processing, I'm getting around 80 million rows.

One field of the processed data is a value of a dictionary, and that field contains multiple value against the key; so during processing, that field's values are stored in a data frame column in list format.

I need to replace that value with the corresponding dictionary key. So I wrote the following function for converting the value to a dictionary key:

def keysWithValue(aDict, target):
    return sorted(key for key, value in aDict.items() if target == value)

I'm feeling that if I will use a for loop for those 80 million records and call this function on each of them, it will take lots of time. Can you please suggest me some alternative Python approach instead of modifying it directly in my database that will save my code running time?

Body:
The fastest you're going to get is to reverse the keys and values to create a value:key lookup map:

rev_dict = {v: k for k, v in aDict.items()}  # use aDict.iteritems() on Python 2.x

UPDATE - if there isn't a 1-to-1 relationship between the key and the value and you have multiple values instead, you can unpack them as:

rev_dict = {i: k for k, v in aDict.items() for i in v}  # use aDict.iteritems() on Python 2.x

Then in your code, when you retrieve the data from your DB, just grab the column value by looking through that lookup map:

column_value = rev_dict.get(column_value, column_value)

Which will give you the key if column_value exists in aDict or will return it's own value unchanged.

Keep in mind, tho, that if your aDict isn't too big, while your approach is a bit wasteful most of the time to process those 80M rows would still be spent on I/O operations.


问:
The requested operation cannot be performed on a file with a user-mapped section open
Whenever I tried to copy 4 files into my bin folder, after stopping the main service, I am getting an error with one file (TexteDll). The error is:

```<code>Cannot copy TexteDll: The requested operation cannot be performed on a file
with a user-mapped section open
</code>```

It may be due to some system locking. Or perhaps another process is using this DLL. When I googled, I found that rebooting the system may resolve this.

Can anybody suggest a cause or solution for this? I inspected the properties of TexteDll (general, version, security, etc). Everything appears normal.

答: in my case deleted the obj folder in project root and rebuild project solved my problem!!!</p>

Body:
Whenever I tried to copy 4 files into my bin folder, after stopping the main service, I am getting an error with one file (TexteDll). The error is:

Cannot copy TexteDll: The requested operation cannot be performed on a file
with a user-mapped section open

It may be due to some system locking. Or perhaps another process is using this DLL. When I googled, I found that rebooting the system may resolve this.

Can anybody suggest a cause or solution for this? I inspected the properties of TexteDll (general, version, security, etc). Everything appears normal.


问:
Bash script doesn't evaluate variable in filename
I have a bash script which creates a backup of my folder. It should name the tar gz file using a version number but it doesn't:

```<code>#!/bin/bash

ver='1.2.3'
tar czf $ver_myfolder.tar.gz .
</code>```

Expected output:

1.2.3_myfolder.tar.gz

Actual output:

_myfolder.tar.gz

If I append the variable like this:

```<code>#!/bin/bash

ver='1.2.3'
tar czf myfolder-$ver.tar.gz .
</code>```

It works

答:
You should use ${var} here since you are appending underscore after it which is considered a valid character for variable names. Due to that fact shell doesn't know whether you're expanding variable name $ver or $ver_myfolder:

```<code>ver='1.2.3'
tar czf "${ver}_myfolder.tar.gz" .
</code>```

Since $ver_myfolder is unset, you get an empty value.

Body:
I have a bash script which creates a backup of my folder. It should name the tar gz file using a version number but it doesn't:

#!/bin/bash

ver='1.2.3'
tar czf $ver_myfolder.tar.gz .

Expected output:

1.2.3_myfolder.tar.gz

Actual output:

_myfolder.tar.gz

If I append the variable like this:

#!/bin/bash

ver='1.2.3'
tar czf myfolder-$ver.tar.gz .

It works

Body:
You should use ${var} here since you are appending underscore after it which is considered a valid character for variable names. Due to that fact shell doesn't know whether you're expanding variable name $ver or $ver_myfolder:

ver='1.2.3'
tar czf "${ver}_myfolder.tar.gz" .

Since $ver_myfolder is unset, you get an empty value.


问:
Ordering and binding in for loop r
I want my for loop to store data in rows, based on the correct order as specified in the for loop, but somehow the data is bound randomly in a new dataframe.

Background information:

I have a dataframe with data from the FMCG industry, amongst this are the prices for products.

My dataframe consists of the top 3 brands of 55 different product categories

In my econometric (marketing) model I also accommodate for competition, so what I do is calculating average prices of the competition of Brand A, B and C based on conditions.

When I run the loop for one category, say category 5 (from my total dataset), I get the right averages in order and stack these, so I can bind them to my main dataframe. This main dataframe has all the brands listed from top to bottom, for every category, for every week.

THE PROBLEM: when I run the for loop, it does calculate the averages, but the final stacked dataframe to bind shuffled all the values so that they are not in order anymore.

So, I need to find a command that keeps my calculated averages in order (so average of competition Category 5 Brand A week 1 as the first row and average of Category 550 Brand C week 208 as last), as happens when I do it for one category, but not in the for loop.

The code:

```<code>##for loop for all competitor average prices accross all categories
    for(X in c("5", "24", "32", "43", "49", "56", "63", "81", "94", "96", "102", "105", "115", "122", "129", "133", "145", "154", "180", "189", "201", "210", "219", "226", "231", "245", "264", "277", "280", "301", "313", "335", "346", "361", "397", "409", "410", "411", "413", "437", "443", "480", "488", "493", "500", "516", "526", "533", "535", "536", "542", "543", "549", "550")){
  PriceX <- read.table(paste0("/Users/censored",X,".csv"), header=TRUE, sep=",")
  PriceX <- transpose(PriceX)
  PriceX <- PriceX[-c(1), ] #deleting the first column of df, contains brand names
  PriceX <- transpose(PriceX)
  PriceX <- sapply(PriceX, as.numeric)
  PriceX <- data.frame(PriceX)
  CompPriceXa <- PriceX[-c(1:2), ] #delete first and second row, contains totals and Brand A
  CompPriceXa <- CompPriceXa %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .))) #Make all zeros NA, otherwise the means are calculated over rows.
  CompPriceXa <- colMeans(CompPriceXa, na.rm=T) #calculate the mean of competitor prices when Brand A is focal brand
  CompPriceXa <- as.matrix(CompPriceXa)
  CompPriceXb <- PriceX[-c(1, 3), ]
   CompPriceXb <- CompPriceXb %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXb <- colMeans(CompPriceXb, na.rm=T)
  CompPriceXb <- as.matrix(CompPriceXb)
  CompPriceXc <- PriceX[-c(1, 4), ]
  CompPriceXc <- CompPriceXc %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXc <- colMeans(CompPriceXc, na.rm=T)
  CompPriceXc <- as.matrix(CompPriceXc)
  StackedCompPrice <- rbind(CompPriceXa, CompPriceXb, CompPriceXc) #stack the average competitor prices of Brand A, B and C.
  StackedCompPrice <- as.data.frame(StackedCompPrice)
  ALLStackedCompPrice <- rbind(StackedCompPrice, ALLStackedCompPrice)}

ALLStackedCompPrice <- StackedCompPrice[NULL,] #first run the for loop, then run this command outside loop to create empty df, then run the forloop again and it will be filled with all the values from all categories
</code>```

Hope you guys can help me out!

Title: Ordering and binding in for loop r

Body:
I want my for loop to store data in rows, based on the correct order as specified in the for loop, but somehow the data is bound randomly in a new dataframe.

Background information:

I have a dataframe with data from the FMCG industry, amongst this are the prices for products.

My dataframe consists of the top 3 brands of 55 different product categories

In my econometric (marketing) model I also accommodate for competition, so what I do is calculating average prices of the competition of Brand A, B and C based on conditions.

When I run the loop for one category, say category 5 (from my total dataset), I get the right averages in order and stack these, so I can bind them to my main dataframe. This main dataframe has all the brands listed from top to bottom, for every category, for every week.

THE PROBLEM: when I run the for loop, it does calculate the averages, but the final stacked dataframe to bind shuffled all the values so that they are not in order anymore.

So, I need to find a command that keeps my calculated averages in order (so average of competition Category 5 Brand A week 1 as the first row and average of Category 550 Brand C week 208 as last), as happens when I do it for one category, but not in the for loop.

The code:

##for loop for all competitor average prices accross all categories
    for(X in c("5", "24", "32", "43", "49", "56", "63", "81", "94", "96", "102", "105", "115", "122", "129", "133", "145", "154", "180", "189", "201", "210", "219", "226", "231", "245", "264", "277", "280", "301", "313", "335", "346", "361", "397", "409", "410", "411", "413", "437", "443", "480", "488", "493", "500", "516", "526", "533", "535", "536", "542", "543", "549", "550")){
  PriceX <- read.table(paste0("/Users/censored",X,".csv"), header=TRUE, sep=",")
  PriceX <- transpose(PriceX)
  PriceX <- PriceX[-c(1), ] #deleting the first column of df, contains brand names
  PriceX <- transpose(PriceX)
  PriceX <- sapply(PriceX, as.numeric)
  PriceX <- data.frame(PriceX)
  CompPriceXa <- PriceX[-c(1:2), ] #delete first and second row, contains totals and Brand A
  CompPriceXa <- CompPriceXa %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .))) #Make all zeros NA, otherwise the means are calculated over rows.
  CompPriceXa <- colMeans(CompPriceXa, na.rm=T) #calculate the mean of competitor prices when Brand A is focal brand
  CompPriceXa <- as.matrix(CompPriceXa)
  CompPriceXb <- PriceX[-c(1, 3), ]
   CompPriceXb <- CompPriceXb %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXb <- colMeans(CompPriceXb, na.rm=T)
  CompPriceXb <- as.matrix(CompPriceXb)
  CompPriceXc <- PriceX[-c(1, 4), ]
  CompPriceXc <- CompPriceXc %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXc <- colMeans(CompPriceXc, na.rm=T)
  CompPriceXc <- as.matrix(CompPriceXc)
  StackedCompPrice <- rbind(CompPriceXa, CompPriceXb, CompPriceXc) #stack the average competitor prices of Brand A, B and C.
  StackedCompPrice <- as.data.frame(StackedCompPrice)
  ALLStackedCompPrice <- rbind(StackedCompPrice, ALLStackedCompPrice)}

ALLStackedCompPrice <- StackedCompPrice[NULL,] #first run the for loop, then run this command outside loop to create empty df, then run the forloop again and it will be filled with all the values from all categories

Hope you guys can help me out!

Body:
This will give an impression of the dataset I do the calculations on:

X Var1 Var2Var3 Var4

1-1 6.584001 6.618493   6.669796 6.14605

2-1 6.316876 6.299771 6.264874 5.531244

3-1
3.914301
3.953827
3.955841
3.640814

4-1
3.629302
3.655962
3.657091
3.525953

5-1
4.801913
4.791146
4.819135
4.888309


问:
how to prevent from exiting or jump out elements from page?
I use several buttons to create motion, now i have a problem when i use marginLeft for move the element to left and right div#ball, it doesn't fit in the page and  jumps out and exit form both left and right side. how i can set a limitation and avoid element from exiting ?

$(document).ready(function() {
  $('#fastleft').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "-=300px"
    });
  });

  $('#moveleft').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "-=20px"
    });
  });

  $('#moveright').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "+=20px"
    });
  });

  $('#fastright').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "+=300px"
    });
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#ball {
  width: 50px;
  height: 50px;
  display: inline-block;
  /*background-image: url(./boll.png);*/
  background-color:red;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  position: relative;
}

.rotated {
  animation-duration: 0.5s;
  animation-name: ball;
}

@keyframes ball {
  0% {
    transform: rotate(100deg)
  }
  25% {
    transform: rotate(200deg)
  }
  50% {
    transform: rotate(300deg)
  }
  100% {
    transform: rotate(360deg)
  }
}</code>```

    <button id="fastleft" type="button">FastLeft</button></button>
    <button id="moveleft" type="button">Left</button>
    <button id="moveright" type="button">Right</button>
    <button id="fastright" type="button">FastRight</button>

```

答: Try using other CSS properties like float and align instead of  giving such large values in pixel to margin or padding properties. This will almost always push your elements out of your page especially if you are working with small screen sizes . Also you should try using bootstrap. It will make your life much easier.</p>

Body:
I use several buttons to create motion, now i have a problem when i use marginLeft for move the element to left and right div#ball, it doesn't fit in the page and  jumps out and exit form both left and right side. how i can set a limitation and avoid element from exiting ?

$(document).ready(function() {
  $('#fastleft').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "-=300px"
    });
  });

  $('#moveleft').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "-=20px"
    });
  });

  $('#moveright').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "+=20px"
    });
  });

  $('#fastright').click(function() {
    $('#ball').toggleClass('rotated');
    $('#ball').animate({
      'marginLeft': "+=300px"
    });
  });

});

#ball {
  width: 50px;
  height: 50px;
  display: inline-block;
  /*background-image: url(./boll.png);*/
  background-color:red;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  position: relative;
}

.rotated {
  animation-duration: 0.5s;
  animation-name: ball;
}

@keyframes ball {
  0% {
    transform: rotate(100deg)
  }
  25% {
    transform: rotate(200deg)
  }
  50% {
    transform: rotate(300deg)
  }
  100% {
    transform: rotate(360deg)
  }
}

    <button id="fastleft" type="button">FastLeft</button></button>
    <button id="moveleft" type="button">Left</button>
    <button id="moveright" type="button">Right</button>
    <button id="fastright" type="button">FastRight</button>


问:
R connecting to Local SQL Server
I cannot connect to my local sql server through Rstudio. I am able to connect to a SQL Server that my company hosts and I can connect to my local SQL Server  through Management Studio. What am I doing wrong?

Is there something I need to do to connect locally? The (LocalDB)\v11.0 was the exact server name that I connect to my local SQL Server through Management Studio.

```<code>install.packages("RODBC")

library(RODBC)

dbconnection <- odbcDriverConnect("Driver=SQL Server;Server=(LocalDB)\v11.0;Database=NBA;trusted_connection=yes")
</code>```

The error message I get is the following:

Warning messages:

  1: In odbcDriverConnect("Driver=SQL Server;Server=(LocalDB)\v11.0;Database=NBA;trusted_connection=yes") :

  [RODBC] ERROR: state 08001, code 17, message [Microsoft][ODBC SQL
  Server Driver][DBNETLIB]SQL Server does not exist or access denied.

2: In odbcDriverConnect("Driver=SQL Server;Server=(LocalDB)\v11.0;Database=NBA;trusted_connection=yes") :

  [RODBC] ERROR: state 01000, code 53, message [Microsoft][ODBC SQL
  Server Driver][DBNETLIB]ConnectionOpen (Connect()).

3: In odbcDriverConnect("Driver=SQL Server;Server=(LocalDB)\v11.0;Database=NBA;trusted_connection=yes") :  ODBC connection failed

答:
try double backslash...
I tried the following and it's working fine:

```<code>library(odbc)
dbconnection <- odbcDriverConnect("Driver=SQL Server;Server=(local)\\SQLSERVER2016;Database=Test_DB;trusted_connection=yes")
data <- sqlFetch(dbconnection, 'dbo.temp_table', colnames=FALSE, rows_at_time=1000)
</code>```

Thanks.

Title: R connecting to Local SQL Server

Body:
I cannot connect to my local sql server through Rstudio. I am able to connect to a SQL Server that my company hosts and I can connect to my local SQL Server  through Management Studio. What am I doing wrong?

Is there something I need to do to connect locally? The (LocalDB)\v11.0 was the exact server name that I connect to my local SQL Server through Management Studio.

install.packages("RODBC")

library(RODBC)

dbconnection <- odbcDriverConnect("Driver=SQL Server;Server=(LocalDB)\v11.0;Database=NBA;trusted_connection=yes")

The error message I get is the following:

Warning messages:

  1: In odbcDriverConnect("Driver=SQL Server;Server=(LocalDB)\v11.0;Database=NBA;trusted_connection=yes") :

  [RODBC] ERROR: state 08001, code 17, message [Microsoft][ODBC SQL
  Server Driver][DBNETLIB]SQL Server does not exist or access denied.

2: In odbcDriverConnect("Driver=SQL Server;Server=(LocalDB)\v11.0;Database=NBA;trusted_connection=yes") :

  [RODBC] ERROR: state 01000, code 53, message [Microsoft][ODBC SQL
  Server Driver][DBNETLIB]ConnectionOpen (Connect()).

3: In odbcDriverConnect("Driver=SQL Server;Server=(LocalDB)\v11.0;Database=NBA;trusted_connection=yes") :  ODBC connection failed

Body:
try double backslash...
I tried the following and it's working fine:

library(odbc)
dbconnection <- odbcDriverConnect("Driver=SQL Server;Server=(local)\\SQLSERVER2016;Database=Test_DB;trusted_connection=yes")
data <- sqlFetch(dbconnection, 'dbo.temp_table', colnames=FALSE, rows_at_time=1000)

Thanks.


问:
Choosing SIM to make a call
I'm really interested in working this out.

I'm developing an app which is supposed to make calls, but the problem starts when device has dual SIM.
After starting Intent.ACTION_CALL activity a dialog pops up to choose the SIM card, I managed not to open that dialog by putting "NOT_NEED_SIMCARD_SELECTION" extra with value: false. But still I don't know how to force slot I want to use.
This should work on API 19.

I found an app Dual SIM Selector where it works perfectly, but I have no idea how they managed it.

答:
I figured it out with help of reflections.
It turns out my device's API was somehow changed and it provides methods like setDefaultSim.

```<code>Method setDefaultSim = TelephonyManager.class.getDeclaredMethod("setDefaultSim", Context.class, int.class, int.class);
setDefaultSim.invoke(null, this, 0, slot);
</code>```

Title: Choosing SIM to make a call

Body:
I figured it out with help of reflections.
It turns out my device's API was somehow changed and it provides methods like setDefaultSim.

Method setDefaultSim = TelephonyManager.class.getDeclaredMethod("setDefaultSim", Context.class, int.class, int.class);
setDefaultSim.invoke(null, this, 0, slot);


问:
Setting android:windowBackground from styles messes up app
I've got a problem with my application. I am trying to make an update for it so that the user can select his own theme for the app. However, that means I have to move the setting of background images from the .xml files to the styles.xml in my theme styles. I did this by removing android:background="@drawable/bg" from my xmls and added <item name="android:windowBackground">@drawable/bg</item> to my style. This looked to be OK in preview but once I ran it in the emulator, whenever I switched fragment, all the contents of the main fragment (loaded on startup) remained in the background at all times...

The we, they, the zeros and all the buttons are from the first fragment but are still visible in this one for some reason...

答: This is because none of your fragments have any background. So when you are adding fragment the content will overlap on one another. Try setting background of the fragments OR you can use replace instead of add fragment.</p>


答:
Because the underscore is a valid character for a variable name, you should use braces to explicitly specify the range of your variable:

```<code>${ver}_myfolder.tar.gz
 ^   ^
</code>```

Without braces, Bash will actually try to parse

```<code>${ver_myfolder}.tar.gz
</code>```

For your edited question, it is because the dot is not a valid character for a variable name, so Bash will not attempt to parse the dot into the name lookup. Even if you put it into braces, a variable name containing a dot is still invalid:

```<code>$ echo ${ver.}
bash: ${ver.}: bad substitution
$ ver.=1.2.3
ver.=1.2.3: command not found
</code>```

Title: Bash script doesn't evaluate variable in filename

Body:
Because the underscore is a valid character for a variable name, you should use braces to explicitly specify the range of your variable:

${ver}_myfolder.tar.gz
 ^   ^

Without braces, Bash will actually try to parse

${ver_myfolder}.tar.gz

For your edited question, it is because the dot is not a valid character for a variable name, so Bash will not attempt to parse the dot into the name lookup. Even if you put it into braces, a variable name containing a dot is still invalid:

$ echo ${ver.}
bash: ${ver.}: bad substitution
$ ver.=1.2.3
ver.=1.2.3: command not found


问:
Improve performance - perhaps parallel implementation
We have a Visual Studio 2017 extension, which creates a solution in VS, loads files from the database into the created project and then compiles it.

This takes a couple of minutes, and I want to do it faster.
I know there are tools out there, I just don't know what to google for exactly.
So I don't expect someone to re-write my code (although a quick example would be great!) but some guidance as to what I could use would be very helpful.

So here we have the method that creates the solution and takes care of loading the files from the database into it:

```<code>public void LoadFilesIntoVS()
    {
        CreateSolution();
        LoadCalcFiles();
        LoadTemplateFiles();
        LoadAdvancedCalcFiles();
        LoadOtherFilesIntoSolution();
    }
</code>```

The four LoadXYZ methods are similar, so I will just continue with an example of LoadCalcFiles().

```<code>public void LoadCalcFiles()
    {
        CalcFilesList = new ObservableCollection<CalcFile>(BuilderService.GetAllCalcFiles());

        foreach (CalcFile file in CalcFilesList)
        {
            LoadCalcFileIntoSolution(file);
        }
    }
</code>```

LoadCalcFileIntoSolution:

```<code>private void LoadCalcFileIntoSolution(CalcFile file)
    {
        try
        {
        string sourcePath = BuilderService.GetCalcFileSourcePath(file.ID);
        string fullName = sourcePath.Substring(sourcePath.LastIndexOf("\\") + 1);
        if (!calcObjects.ContainsKey(fullName))
        {

            if (!File.Exists(sourcePath))
            {
                BuilderService.GenerateCalcFileMethod(file.ID);
            }

            ProjectItem calcFile = LoadAsProjectItem(sourcePath);
            calcObjects.Add(fullName, file);
        }
      }
        catch (Exception e)
        {
            SetErrorStatus("Problem loading CalcFile into Solution. " + e.Message);
        }
    }
</code>```

So yes, I've heard of a parallel foreach. Would it be beneficial to use that in LoadCalcFiles?
Also, could I somehow run the four LoadXYZ methods at the same time after creating the solution?

答:
Try this:</p>

```<code>public void LoadFilesIntoVS()
    {
        CreateSolution();
        new Thread(LoadCalcFiles).        Start();
        new Thread(LoadTemplateFiles).    Start();
        new Thread(LoadAdvancedCalcFiles).Start();
        LoadOtherFilesIntoSolution();
    }
</code>```

Body:
We have a Visual Studio 2017 extension, which creates a solution in VS, loads files from the database into the created project and then compiles it.

This takes a couple of minutes, and I want to do it faster.
I know there are tools out there, I just don't know what to google for exactly.
So I don't expect someone to re-write my code (although a quick example would be great!) but some guidance as to what I could use would be very helpful.

So here we have the method that creates the solution and takes care of loading the files from the database into it:

public void LoadFilesIntoVS()
    {
        CreateSolution();
        LoadCalcFiles();
        LoadTemplateFiles();
        LoadAdvancedCalcFiles();
        LoadOtherFilesIntoSolution();
    }

The four LoadXYZ methods are similar, so I will just continue with an example of LoadCalcFiles().

public void LoadCalcFiles()
    {
        CalcFilesList = new ObservableCollection<CalcFile>(BuilderService.GetAllCalcFiles());

        foreach (CalcFile file in CalcFilesList)
        {
            LoadCalcFileIntoSolution(file);
        }
    }

LoadCalcFileIntoSolution:

private void LoadCalcFileIntoSolution(CalcFile file)
    {
        try
        {
        string sourcePath = BuilderService.GetCalcFileSourcePath(file.ID);
        string fullName = sourcePath.Substring(sourcePath.LastIndexOf("\\") + 1);
        if (!calcObjects.ContainsKey(fullName))
        {

            if (!File.Exists(sourcePath))
            {
                BuilderService.GenerateCalcFileMethod(file.ID);
            }

            ProjectItem calcFile = LoadAsProjectItem(sourcePath);
            calcObjects.Add(fullName, file);
        }
      }
        catch (Exception e)
        {
            SetErrorStatus("Problem loading CalcFile into Solution. " + e.Message);
        }
    }

So yes, I've heard of a parallel foreach. Would it be beneficial to use that in LoadCalcFiles?
Also, could I somehow run the four LoadXYZ methods at the same time after creating the solution?

Body:
Try this:

public void LoadFilesIntoVS()
    {
        CreateSolution();
        new Thread(LoadCalcFiles).        Start();
        new Thread(LoadTemplateFiles).    Start();
        new Thread(LoadAdvancedCalcFiles).Start();
        LoadOtherFilesIntoSolution();
    }


问:
How can an expression be different from however paarenthesized?

Consider this statement:

> False == False in [False]
True
```

<p>However:</p>

<pre class="lang-python prettyprint-override"><code>> (False == False) in [False]
False
> False == (False in [False])
False
</code>```

It is incredible. What's the reason and the interpretation?

答:
dis.dis to the rescue and a bit of my interpretation.

Anyway, it looks like this. Consider three expression X, Y, Z and two operators O1, O2. Then

```<code>X O1 Y O2 Z
</code>```

is equivalent to

```<code>(X O1 Y) and (Y O2 Z)
</code>```

as can be seen by

```<code>a < b < c
</code>```

example. I find this behaviour very counterintuitive.

And the docs:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Note that in is a comparison operator.

Body:
Consider this statement:

> False == False in [False]
True

However:

> (False == False) in [False]
False
> False == (False in [False])
False

It is incredible. What's the reason and the interpretation?

Body:
dis.dis to the rescue and a bit of my interpretation.

Anyway, it looks like this. Consider three expression X, Y, Z and two operators O1, O2. Then

X O1 Y O2 Z

is equivalent to

(X O1 Y) and (Y O2 Z)

as can be seen by

a < b < c

example. I find this behaviour very counterintuitive.

And the docs:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Note that in is a comparison operator.


问:
Where does Asp.Net UserAuthentication store users?
I was checking up to create a login system, now I found this standard login from Visual Studio. this link Authentication Methods I chose Individual User Accounts.

Now I'm curious to know where the data is saved.

I made a registration to the program afterwards I closed the app, hosted it again on my localhost and I still could log in with the same account.

I debugged the code, but it refers to the dll: Microsoft.AspNet.Identity.Core
I checked my local database but there are no users.
Removed the local database, still able to log in or register

答:
I got the connectionString in de webconfig file!
I managed to change the string to my own database and the program does the rest!  </p>


问:
Getting an "expected identified" error when it perfectly on an IDE
I'm using SSH Secure Shell to run and submit my assignment.  I'm getting this error right now:

In file included from a1ms4.c:15:0:
contacts.h:37:4: error: expected identifier or â(â before â--â token
In file included from contacts.c:16:0:
contacts.h:37:4: error: expected identifier or â(â before â--â token

Which is bogus because the exact same code compiled on another IDE.  These are my C files that are reporting the error.  I am not missing a ( or a { or a ; anywhere in my code.  I went through this code for hours to find a potential mistake but couldn't spot anything and despite that, it won't let me submit my assignment.

a1ms4.c

```<code>#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include "contacts.h"

int main(void)
{
    struct Contact contact;

    printf("Contact Management System\n-------------------------\n");

    getName(&contact.name);

    getAddress(&contact.address);

    getNumbers(&contact.numbers);

    printf("\nContact Details\n---------------");

    printf("\nName Details");

    printf("\nFirst name: %s", contact.name.firstName);

    printf("\nMiddle initial(s): %s", contact.name.middleInitial);

    printf("\nLast name: %s", contact.name.lastName);

    printf("\n");

    printf("\nAddress Details");

    printf("\nStreet number: %d", contact.address.streetNumber);

    printf("\nStreet name: %s", contact.address.street);

    printf("\nApartment: %d", contact.address.apartmentNumber);

    printf("\nPostal code: %s", contact.address.postalCode);

    printf("\nCity: %s", contact.address.city);

    printf("\n");

    printf("\nPhone Numbers:");

    printf("\nCell phone number: %s", contact.numbers.cell);

    printf("\nHome phone number: %s", contact.numbers.home);

    printf("\nBusiness phone number: %s", contact.numbers.business);

    printf("\n");

    printf("\nStructure test for Contact using functions done!\n");

    return 0;
}
</code>```

contacts.c

```<code>#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#include "contacts.h"

void getName(struct Name *name) {
    char one;
    struct Name temporaryName;

    printf("Please enter the contact's first name: ");
    scanf(" %[^\n]", temporaryName.firstName);
    printf("Do you want to enter a middle initial(s)? (y or n): ");
    scanf(" %c", &one);

    if (one == 'y' || one == 'Y') {
        printf("Please enter the contact's middle initial(s): ");
        scanf(" %[^\n]", temporaryName.middleInitial);
    }

    printf("Please enter the contact's last name: ");
    scanf(" %[^\n]", temporaryName.lastName);

    *name = temporaryName;

    return;
}

void getAddress(struct Address *address) {
    char two;
    struct Address temporaryAddress;

    printf("Please enter the contact's street number: ");
    scanf("%d", &temporaryAddress.streetNumber);

    printf("Please enter the contact's street name: ");
    scanf(" %[^\n]", temporaryAddress.street);

    printf("Do you want to enter an appartment number? (y or n): ");
    scanf(" %c", &two);

    if (two == 'y' || two == 'Y') {
        printf("Please enter the contact's appartment number: ");
        scanf(" %d", &temporaryAddress.apartmentNumber);
    }

    printf("Please enter the contact's postal code: ");
    scanf(" %[^\n]", temporaryAddress.postalCode);

    printf("Please enter the contact's city: ");
    scanf(" %[^\n]", temporaryAddress.city);

    *address = temporaryAddress;

    return;
}

void getNumbers(struct Numbers *numbers) {
    char three, four, five;
    struct Numbers temporaryNumbers;

    printf("Do you want to enter a cell phone number? (y or n): ");
    scanf(" %c", &three);

    if (three == 'y' || three == 'Y') {
        printf("Please enter the contact's cell phone number: ");
        scanf(" %[^\n]", temporaryNumbers.cell);
    }

    printf("Do you want to enter a home phone number? (y or n): ");
    scanf(" %c", &four);

    if (four == 'y' || four == 'Y') {
        printf("Please enter the contact's home phone number: ");
        scanf(" %[^\n]", temporaryNumbers.home);
    }

    printf("Do you want to enter a business phone number? (y or n): ");
    scanf(" %c", &five);

    if (five == 'y' || five == 'Y') {
        printf("Please enter the contact's business phone number: ");
        scanf(" %[^\n]", temporaryNumbers.business);
    }

    *numbers = temporaryNumbers;
    return;
}
</code>```

contacts.h

```<code>/* -------------------------------------------
Name:
Student number:
Email:
Section:
Date:
----------------------------------------------
Assignment: 1
Milestone:  4
---------------------------------------------- */

struct Name {
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

struct Address {
    int streetNumber;
    char street[41];
    int apartmentNumber;
    char postalCode[8];
    char city[41];
};

struct Numbers {
    char cell[21];
    char home[21];
    char business[21];
};

//This is a structure that includes the 3 previous structures.
struct Contact {
    struct Name name;
    struct Address address;
    struct Numbers numbers;
};
</code>```

答:
regarding contacts.h

it is missing the multiple include guard.

```<code>#ifndef CONTACTS_H
#define CONTACTS_H
....
#endif // CONTACTS_H
</code>```

it is missing the prototypes for the functions in contacts.c

```<code>void getName(struct Name *name);
void getAddress(struct Address *address);
void getNumbers(struct Numbers *numbers);
</code>```

The contacts.h file should look like the following:

```<code>/* -------------------------------------------
Name:
Student number:
Email:
Section:
Date:
----------------------------------------------
Assignment: 1
Milestone:  4
---------------------------------------------- */

#ifndef CONTACTS_H
#define CONTACTS_H

struct Name
{
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

struct Address
{
    int streetNumber;
    char street[41];
    int apartmentNumber;
    char postalCode[8];
    char city[41];
};

struct Numbers
{
    char cell[21];
    char home[21];
    char business[21];
};

//This is a structure that includes the 3 previous structures.
struct Contact
{
    struct Name name;
    struct Address address;
    struct Numbers numbers;
};

// prototypes for functions in contacts.c
void getName(struct Name *name);
void getAddress(struct Address *address);
void getNumbers(struct Numbers *numbers);

#endif // CONTACTS_H
</code>```

After making the above changes to contacts.h, the code cleanly compiles

Body:
I'm using SSH Secure Shell to run and submit my assignment.  I'm getting this error right now:

In file included from a1ms4.c:15:0:
contacts.h:37:4: error: expected identifier or â(â before â--â token
In file included from contacts.c:16:0:
contacts.h:37:4: error: expected identifier or â(â before â--â token

Which is bogus because the exact same code compiled on another IDE.  These are my C files that are reporting the error.  I am not missing a ( or a { or a ; anywhere in my code.  I went through this code for hours to find a potential mistake but couldn't spot anything and despite that, it won't let me submit my assignment.

a1ms4.c

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include "contacts.h"

int main(void)
{
    struct Contact contact;

    printf("Contact Management System\n-------------------------\n");

    getName(&contact.name);

    getAddress(&contact.address);

    getNumbers(&contact.numbers);

    printf("\nContact Details\n---------------");

    printf("\nName Details");

    printf("\nFirst name: %s", contact.name.firstName);

    printf("\nMiddle initial(s): %s", contact.name.middleInitial);

    printf("\nLast name: %s", contact.name.lastName);

    printf("\n");

    printf("\nAddress Details");

    printf("\nStreet number: %d", contact.address.streetNumber);

    printf("\nStreet name: %s", contact.address.street);

    printf("\nApartment: %d", contact.address.apartmentNumber);

    printf("\nPostal code: %s", contact.address.postalCode);

    printf("\nCity: %s", contact.address.city);

    printf("\n");

    printf("\nPhone Numbers:");

    printf("\nCell phone number: %s", contact.numbers.cell);

    printf("\nHome phone number: %s", contact.numbers.home);

    printf("\nBusiness phone number: %s", contact.numbers.business);

    printf("\n");

    printf("\nStructure test for Contact using functions done!\n");

    return 0;
}

contacts.c

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#include "contacts.h"

void getName(struct Name *name) {
    char one;
    struct Name temporaryName;

    printf("Please enter the contact's first name: ");
    scanf(" %[^\n]", temporaryName.firstName);
    printf("Do you want to enter a middle initial(s)? (y or n): ");
    scanf(" %c", &one);

    if (one == 'y' || one == 'Y') {
        printf("Please enter the contact's middle initial(s): ");
        scanf(" %[^\n]", temporaryName.middleInitial);
    }

    printf("Please enter the contact's last name: ");
    scanf(" %[^\n]", temporaryName.lastName);

    *name = temporaryName;

    return;
}

void getAddress(struct Address *address) {
    char two;
    struct Address temporaryAddress;

    printf("Please enter the contact's street number: ");
    scanf("%d", &temporaryAddress.streetNumber);

    printf("Please enter the contact's street name: ");
    scanf(" %[^\n]", temporaryAddress.street);

    printf("Do you want to enter an appartment number? (y or n): ");
    scanf(" %c", &two);

    if (two == 'y' || two == 'Y') {
        printf("Please enter the contact's appartment number: ");
        scanf(" %d", &temporaryAddress.apartmentNumber);
    }

    printf("Please enter the contact's postal code: ");
    scanf(" %[^\n]", temporaryAddress.postalCode);

    printf("Please enter the contact's city: ");
    scanf(" %[^\n]", temporaryAddress.city);

    *address = temporaryAddress;

    return;
}

void getNumbers(struct Numbers *numbers) {
    char three, four, five;
    struct Numbers temporaryNumbers;

    printf("Do you want to enter a cell phone number? (y or n): ");
    scanf(" %c", &three);

    if (three == 'y' || three == 'Y') {
        printf("Please enter the contact's cell phone number: ");
        scanf(" %[^\n]", temporaryNumbers.cell);
    }

    printf("Do you want to enter a home phone number? (y or n): ");
    scanf(" %c", &four);

    if (four == 'y' || four == 'Y') {
        printf("Please enter the contact's home phone number: ");
        scanf(" %[^\n]", temporaryNumbers.home);
    }

    printf("Do you want to enter a business phone number? (y or n): ");
    scanf(" %c", &five);

    if (five == 'y' || five == 'Y') {
        printf("Please enter the contact's business phone number: ");
        scanf(" %[^\n]", temporaryNumbers.business);
    }

    *numbers = temporaryNumbers;
    return;
}

contacts.h

/* -------------------------------------------
Name:
Student number:
Email:
Section:
Date:
----------------------------------------------
Assignment: 1
Milestone:  4
---------------------------------------------- */

struct Name {
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

struct Address {
    int streetNumber;
    char street[41];
    int apartmentNumber;
    char postalCode[8];
    char city[41];
};

struct Numbers {
    char cell[21];
    char home[21];
    char business[21];
};

//This is a structure that includes the 3 previous structures.
struct Contact {
    struct Name name;
    struct Address address;
    struct Numbers numbers;
};

Body:
regarding contacts.h

it is missing the multiple include guard.

#ifndef CONTACTS_H
#define CONTACTS_H
....
#endif // CONTACTS_H

it is missing the prototypes for the functions in contacts.c

void getName(struct Name *name);
void getAddress(struct Address *address);
void getNumbers(struct Numbers *numbers);

The contacts.h file should look like the following:

/* -------------------------------------------
Name:
Student number:
Email:
Section:
Date:
----------------------------------------------
Assignment: 1
Milestone:  4
---------------------------------------------- */

#ifndef CONTACTS_H
#define CONTACTS_H

struct Name
{
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

struct Address
{
    int streetNumber;
    char street[41];
    int apartmentNumber;
    char postalCode[8];
    char city[41];
};

struct Numbers
{
    char cell[21];
    char home[21];
    char business[21];
};

//This is a structure that includes the 3 previous structures.
struct Contact
{
    struct Name name;
    struct Address address;
    struct Numbers numbers;
};

// prototypes for functions in contacts.c
void getName(struct Name *name);
void getAddress(struct Address *address);
void getNumbers(struct Numbers *numbers);

#endif // CONTACTS_H

After making the above changes to contacts.h, the code cleanly compiles


问:
Word VBA to Save in specific Directory with Merge Field as File Name and Prompt
Background:
I have created an Excel template to mail merge the fields into a Word document and generate 5 different letters which would go out to ONE customer.

Mission:
To have the Word VBA code run an automatic mail merge and prompt to save (or Autosave) in a specific directory with a file name which is derived from a mail merge field.

ie.

(unique identifier) + Name of First Letter + Date
to be saved in First Letter Folder

(unique identifier) + Name of Second Letter + Date
to be saved in Second Letter Folder

etc..

Issue:
I cannot figure out how to specify the directory or how to insert a mail merge field as a part of the file name.

The following is the code that I have

```<code>Sub MailMerge()

With ActiveDocument.MailMerge
    .Destination = wdSendToNewDocument
    .SuppressBlankLines = True

    With .DataSource
        .FirstRecord = wdDefaultFirstRecord
        .LastRecord = wdDefaultLastRecord
    End With

    .Execute Pause:=False
End With

With Dialogs(wdDialogFileSummaryInfo)
    .Title = "Letter1Draft" & Format(Now(), "mmddyyyy") & ".doc"
    .Execute
End With

' Then this!
With Dialogs(wdDialogFileSaveAs)
    .Show
End With

End Sub
</code>```

答:
The following code picks the directory.
It does not allow you to insert a mail merge field as the file name.    </p>

```<code>Sub AllSectionsToSubDoc()

    Dim x               As Long
    Dim Sections        As Long
    Dim Doc             As Document

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Set Doc = ActiveDocument
    Sections = Doc.Sections.Count
    For x = Sections - 1 To 1 Step -1
        Doc.Sections(x).Range.Copy
        Documents.Add
        ActiveDocument.Range.Paste
        ActiveDocument.SaveAs (Doc.Path & "\" & x & ".pdf")
        ActiveDocument.Close False
    Next x

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True

End Sub
</code>```

Body:
Background:
I have created an Excel template to mail merge the fields into a Word document and generate 5 different letters which would go out to ONE customer.

Mission:
To have the Word VBA code run an automatic mail merge and prompt to save (or Autosave) in a specific directory with a file name which is derived from a mail merge field.

ie.

(unique identifier) + Name of First Letter + Date
to be saved in First Letter Folder

(unique identifier) + Name of Second Letter + Date
to be saved in Second Letter Folder

etc..

Issue:
I cannot figure out how to specify the directory or how to insert a mail merge field as a part of the file name.

The following is the code that I have

Sub MailMerge()

With ActiveDocument.MailMerge
    .Destination = wdSendToNewDocument
    .SuppressBlankLines = True

    With .DataSource
        .FirstRecord = wdDefaultFirstRecord
        .LastRecord = wdDefaultLastRecord
    End With

    .Execute Pause:=False
End With

With Dialogs(wdDialogFileSummaryInfo)
    .Title = "Letter1Draft" & Format(Now(), "mmddyyyy") & ".doc"
    .Execute
End With

' Then this!
With Dialogs(wdDialogFileSaveAs)
    .Show
End With

End Sub

Body:
The following code picks the directory.
It does not allow you to insert a mail merge field as the file name.

Sub AllSectionsToSubDoc()

    Dim x               As Long
    Dim Sections        As Long
    Dim Doc             As Document

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Set Doc = ActiveDocument
    Sections = Doc.Sections.Count
    For x = Sections - 1 To 1 Step -1
        Doc.Sections(x).Range.Copy
        Documents.Add
        ActiveDocument.Range.Paste
        ActiveDocument.SaveAs (Doc.Path & "\" & x & ".pdf")
        ActiveDocument.Close False
    Next x

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True

End Sub


问:
express js not serving the static css files from router
I am actually facing this problem in another bigger project but, I have made a simple one so as to explain it easily

Tree Structure of my project is as follows

```<code>demo
|____admin
|         |____admin.js
|____node_modules
|
|____static
|         |____bootstrap.min.css
|         |____headerStyle.min.css
|
|____views
|    |____admin
|    |    |____admin_home.ejs
|    |
|    |____partials
|                 |____admin_header.ejs
|
|____index.js
|____package-lock.json
|____package.json
</code>```

please bear with me, I am going to post the code of some of important files

code in 'index.js' is this

```<code>let express = require('express');
let app = express();
let path = require('path');

app.use(express.static(path.join(__dirname, 'static')));
app.set('view engine', 'ejs');
app.get('/',function(req,res)
{
  res.render('./admin/admin_home');
});

let admin = require('./admin/admin.js');
app.use('/admin',admin);

app.listen(9000,function(){
  console.log('listening to port : 9000');
});
</code>```

Code in 'admin/admin.js' is this

```<code>let express = require('express');
let router = express.Router();

router.get('/',function(req,res)
{
  res.render('./admin/admin_home');
});

router.get('/adminhome',function(req,res)
{
  res.render('./admin/admin_home');
});

module.exports = router;
</code>```

Code in 'views/admin/admin.ejs' is this

```<code><%- include('../partials/admin_header.ejs')  %>

<h1>Admin Home</h1>
</code>```

I am having problem with express js static file serving.

For the following URL's the webpages are rendered with all the styles from css files

```<code>http://localhost:9000
http://localhost:9000/admin
</code>```

they are served from these paths

```<code>http://localhost:9000/bootstrap.min.css
</code>```

and

```<code>http://localhost:9000/headerStyle.css
</code>```

but for the following URL webpages are rendered with plain html with out serving the css syles

```<code>http://localhost:9000/admin/adminhome
</code>```

the error is

```<code>Failed to load the resources: the server responded with 404
</code>```

css files are served from these paths

```<code>http://localhost:9000/admin/bootstrap.min.css
</code>```

and

```<code>http://localhost:9000/admin/headerStyle.css
</code>```

and the 'Link' tags in 'vies/partials/admin_header.ejs' are as follows

```<code><link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="headerStyle.css">
</code>```

versions of the modules are as follows

```<code>ejs:^2.5.7
express:^4.16.2
path:^0.12.7
</code>```

my nodejs version is
    v8.5.0

Please help me in finding the solution for this problem. Thank You

答:
as quoted by Roland Starke, the hrefs of the styles were relative to the url I was  visiting. I can make them absolute just by adding a ' / ' like </p>

```<code>href="/bootstrap.min.css"
</code>```

Body:
I am actually facing this problem in another bigger project but, I have made a simple one so as to explain it easily

Tree Structure of my project is as follows

demo
|____admin
|         |____admin.js
|____node_modules
|
|____static
|         |____bootstrap.min.css
|         |____headerStyle.min.css
|
|____views
|    |____admin
|    |    |____admin_home.ejs
|    |
|    |____partials
|                 |____admin_header.ejs
|
|____index.js
|____package-lock.json
|____package.json

please bear with me, I am going to post the code of some of important files

code in 'index.js' is this

let express = require('express');
let app = express();
let path = require('path');

app.use(express.static(path.join(__dirname, 'static')));
app.set('view engine', 'ejs');
app.get('/',function(req,res)
{
  res.render('./admin/admin_home');
});

let admin = require('./admin/admin.js');
app.use('/admin',admin);

app.listen(9000,function(){
  console.log('listening to port : 9000');
});

Code in 'admin/admin.js' is this

let express = require('express');
let router = express.Router();

router.get('/',function(req,res)
{
  res.render('./admin/admin_home');
});

router.get('/adminhome',function(req,res)
{
  res.render('./admin/admin_home');
});

module.exports = router;

Code in 'views/admin/admin.ejs' is this

<%- include('../partials/admin_header.ejs')  %>

Admin Home

I am having problem with express js static file serving.

For the following URL's the webpages are rendered with all the styles from css files

http://localhost:9000
http://localhost:9000/admin

they are served from these paths

http://localhost:9000/bootstrap.min.css

and

http://localhost:9000/headerStyle.css

but for the following URL webpages are rendered with plain html with out serving the css syles

http://localhost:9000/admin/adminhome

the error is

Failed to load the resources: the server responded with 404

css files are served from these paths

http://localhost:9000/admin/bootstrap.min.css

and

http://localhost:9000/admin/headerStyle.css

and the 'Link' tags in 'vies/partials/admin_header.ejs' are as follows

<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="headerStyle.css">

versions of the modules are as follows

ejs:^2.5.7
express:^4.16.2
path:^0.12.7

my nodejs version is
    v8.5.0

Please help me in finding the solution for this problem. Thank You

Body:
as quoted by Roland Starke, the hrefs of the styles were relative to the url I was  visiting. I can make them absolute just by adding a ' / ' like

href="/bootstrap.min.css"


问:
Get the length of a String
How do you get the length of a String? For example, I have a variable defined like:

```<code>var test1: String = "Scott"
</code>```

However, I can't seem to find a length method on the string.

答:
In Swift 4 :
If the string does not contain unicode characters then use the following

```<code>let str : String = "abcd"
let count = str.count // output 4
</code>```

If the string contains unicode chars then use the following :

```<code>let spain = "España"
let count1 = spain.count // output 6
let count2 = spain.utf8.count // output 7
</code>```

Title: Get the length of a String

Body:
How do you get the length of a String? For example, I have a variable defined like:

var test1: String = "Scott"

However, I can't seem to find a length method on the string.

Body:
In Swift 4 :
If the string does not contain unicode characters then use the following

let str : String = "abcd"
let count = str.count // output 4

If the string contains unicode chars then use the following :

let spain = "España"
let count1 = spain.count // output 6
let count2 = spain.utf8.count // output 7


问:
How to set mongod.conf bind_ip with multiple ip address
I am a newbie for setting up the server environment and mongoDB. This may sounds something really simple, however, I really need your help on it.

I am trying to connect to my virtual machine which runs the mongodb instance from the local machine, which I believe should be similar to the production environment when I run it on a separate remote server.

The environment is as following:

Private IP for virtual machine: 192.168.184.155

Public IP for both local machine and virtual machine: 96.88.169.145

I changed the bind_ip in /etc/mongod.conf file from

```<code>bind_ip = 127.0.0.1
</code>```

to

```<code>bind_ip = 127.0.0.1,192.168.184.155,96.88.169.145
</code>```

After I restarted the mongod service, neither the virtual machine nor the local machine can access mongodb through mongodb command and giving me the following error.

```<code>MongoDB shell version: 3.0.1
connecting to: test
2015-03-17T16:02:22.705-0400 W NETWORK  Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused
2015-03-17T16:02:22.707-0400 E QUERY    Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed
    at connect (src/mongo/shell/mongo.js:179:14)
    at (connect):1:6 at src/mongo/shell/mongo.js:179
exception: connect failed
</code>```

However, if I change the

```<code>bind_ip = 192.168.184.155
</code>```

and restart the service, it works and I can access using mongo from my local machine. It seems just not work with multiple ip addresses. I tried to do look up in the mongodb document, however, they does mention that bind_ip takes a comma separated list, which really confused me.

Thanks for your help in advance.

Body:
I am a newbie for setting up the server environment and mongoDB. This may sounds something really simple, however, I really need your help on it.

I am trying to connect to my virtual machine which runs the mongodb instance from the local machine, which I believe should be similar to the production environment when I run it on a separate remote server.

The environment is as following:

Private IP for virtual machine: 192.168.184.155

Public IP for both local machine and virtual machine: 96.88.169.145

I changed the bind_ip in /etc/mongod.conf file from

bind_ip = 127.0.0.1

to

bind_ip = 127.0.0.1,192.168.184.155,96.88.169.145

After I restarted the mongod service, neither the virtual machine nor the local machine can access mongodb through mongodb command and giving me the following error.

MongoDB shell version: 3.0.1
connecting to: test
2015-03-17T16:02:22.705-0400 W NETWORK  Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused
2015-03-17T16:02:22.707-0400 E QUERY    Error: couldn't connect to server 127.0.0.1:27017 (127.0.0.1), connection attempt failed
    at connect (src/mongo/shell/mongo.js:179:14)
    at (connect):1:6 at src/mongo/shell/mongo.js:179
exception: connect failed

However, if I change the

bind_ip = 192.168.184.155

and restart the service, it works and I can access using mongo from my local machine. It seems just not work with multiple ip addresses. I tried to do look up in the mongodb document, however, they does mention that bind_ip takes a comma separated list, which really confused me.

Thanks for your help in advance.

Body:
In Mongo 3.*,

use a bracket such as

net:
    port: 27017
    bindIp : [127.0.0.1,10.0.0.2,10.0.0.3]


问:
Give margin to canvas tag in pdf using jspdf
I want to give a margin to the canvas tag so it doesn't overlap the header and its contents.

```<code><script>
 $('#cmd').click(function() {
  var pdf = new jsPDF('p', 'pt', 'letter');
  var options = {
   pagesplit: true,
  };

  try {
   canvas.getContext('2d');
   var imgData = canvas.toDataURL("image/png", 1.0);
   pdf.addImage(imgData, 'JPEG', 5, 5);
  }
  catch(e) {
   alert("Error description: " + e.message);
 }
 source = $('#content')[0];
 specialElementHandlers = {
   'img' : function(element, renderer){
     return true;
   }
 };
 margins = {
   top: 0,
   bottom: 0,
   left: 25,
   width: 522
 };
 pdf.fromHTML(
   source, // HTML string or DOM elem ref.
   margins.left, // x coord
   margins.top, { // y coord
     'width': margins.width, // max width of content on PDF
     'elementHandlers': specialElementHandlers
   },enter code here

   function (dispose) {

     pdf.save('Test.pdf');
   }, margins);
 });
</script>
</code>```

I want that there is no overlapping btw the canvas tag (image) and header and footer be permanent on every pdf page.

答:
```<code><script>
 $('#cmd').click(function() {
  var pdf = new jsPDF('p', 'pt', 'letter');
  var options = {
   pagesplit: true,
  };

   canvas.getContext('2d');
   var imgData = canvas.toDataURL("image/png", 1.0);
   pdf.addImage(imgData, 'JPEG', 0, 200);

 source = $('#content')[0];
 specialElementHandlers = {
   'img' : function(element, renderer){
     return true;
   }
 };
 margins = {
   top: 0,
   bottom: 0,
   left: 25,
   width: 522
 };
 pdf.fromHTML(
   source, // HTML string or DOM elem ref.
   margins.left, // x coord
   margins.top, { // y coord
     'width': margins.width, // max width of content on PDF
     'elementHandlers': specialElementHandlers
   },enter code here

   function (dispose) {

     pdf.save('Test.pdf');
   }, margins);
 });
</script>
</code>```

Body:
I want to give a margin to the canvas tag so it doesn't overlap the header and its contents.

I want that there is no overlapping btw the canvas tag (image) and header and footer be permanent on every pdf page.


问:
Can't find the 'libpq-fe.h header when trying to install pg gem
I am using the Ruby on Rails 3.1 pre version. I like to use PostgreSQL, but the problem is installing the pg gem. It gives me the following error:

$ gem install pg
Building native extensions.  This could take a while...
ERROR:  Error installing pg:
    ERROR: Failed to build gem native extension.

        /home/u/.rvm/rubies/ruby-1.9.2-p0/bin/ruby extconf.rb
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/home/u/.rvm/rubies/ruby-1.9.2-p0/bin/ruby
    --with-pg
    --without-pg
    --with-pg-dir
    --without-pg-dir
    --with-pg-include
    --without-pg-include=${pg-dir}/include
    --with-pg-lib
    --without-pg-lib=${pg-dir}/lib
    --with-pg-config
    --without-pg-config
    --with-pg_config
    --without-pg_config
    Gem files will remain installed in /home/u/.rvm/gems/ruby-1.9.2-p0/gems/pg-0.11.0 for inspection.
    Results logged to /home/u/.rvm/gems/ruby-1.9.2-p0/gems/pg-0.11.0/ext/gem_make.out
```

How do I solve this problem?

答:
For MacOS without installing PostgreSQL server:

```<code>brew install libpq
gem install pg -- --with-pg-config="/usr/local/Cellar/libpq/9.6.6/bin/pg_config"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using the Ruby on Rails 3.1 pre version. I like to use PostgreSQL, but the problem is installing the pg gem. It gives me the following error:

$ gem install pg
Building native extensions.  This could take a while...
ERROR:  Error installing pg:
    ERROR: Failed to build gem native extension.

        /home/u/.rvm/rubies/ruby-1.9.2-p0/bin/ruby extconf.rb
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
 --with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/home/u/.rvm/rubies/ruby-1.9.2-p0/bin/ruby
    --with-pg
    --without-pg
    --with-pg-dir
    --without-pg-dir
    --with-pg-include
    --without-pg-include=${pg-dir}/include
    --with-pg-lib
    --without-pg-lib=${pg-dir}/lib
    --with-pg-config
    --without-pg-config
    --with-pg_config
    --without-pg_config
    Gem files will remain installed in /home/u/.rvm/gems/ruby-1.9.2-p0/gems/pg-0.11.0 for inspection.
    Results logged to /home/u/.rvm/gems/ruby-1.9.2-p0/gems/pg-0.11.0/ext/gem_make.out

How do I solve this problem?

Body:
For MacOS without installing PostgreSQL server:

brew install libpq
gem install pg -- --with-pg-config="/usr/local/Cellar/libpq/9.6.6/bin/pg_config"


问:
Catching command-line errors using %x
Whenever you want to execute something on the command line, you can use the following syntax:

```<code>%x(command to run)
</code>```

However, I want to catch an error or at least get the response so I can parse it correctly. I tried setting:

```<code>result = %x(command to run)
</code>```

and using a try-catch

```<code>begin
  %x(command to run)
rescue
  "didn't work"
end
</code>```

to no avail. How can I capture the results instead of having them printed out?

答:
You need a mix of @Cam 's answer and @tonttu 's answer.

decent explanation of $? and others.

Edit: the domain http://blog.purifyapp.com is now in hands of a domain-squatter and scammer.

```<code>result = %x(command to run 2>&1)

unless $? == 0 #check if the child process exited cleanly.
    puts "got error #{result}"
end
</code>```

ContentLicense: CC BY-SA 2.5

Title: Catching command-line errors using %x

Body:
Whenever you want to execute something on the command line, you can use the following syntax:

%x(command to run)

However, I want to catch an error or at least get the response so I can parse it correctly. I tried setting:

result = %x(command to run)

and using a try-catch

begin
  %x(command to run)
rescue
  "didn't work"
end

to no avail. How can I capture the results instead of having them printed out?

Body:
You need a mix of @Cam 's answer and @tonttu 's answer.

decent explanation of $? and others.

Edit: the domain http://blog.purifyapp.com is now in hands of a domain-squatter and scammer.

result = %x(command to run 2>&1)

unless $? == 0 #check if the child process exited cleanly.
    puts "got error #{result}"
end


问:
What's wrong with this layout that's causing the elevation shadow not to appear?

I'm trying to use Android Elevation to achieve the 'shadow' look for a view. The following is the layout xml:

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.sample.app.Main2Activity">

    <LinearLayout
        android:layout_width="395dp"
        android:layout_height="match_parent"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:orientation="vertical"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:clipChildren="false">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="165dp"
            android:background="#FFFFFF"
            android:padding="30dp"
            android:layout_margin="30dp"
            android:elevation="10dp"
            android:text="TextView" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>
</code>```

This is how the layout looks:
Look ma, no shadows!

Any suggestions to fix this?

答:
I'll get to the answer, but some background first. I was trying to achieve the look with a custom view that used a ConstraintLayout. This view would be used in another layout. I was when I tried using a simple TextView that I realised that the shadows weren't being rendered because, thus destroying my assumption that it was something ConstraintLayout related.

What worked?
I know, from the documentations, that shadows and rendered using a View's background. This, I have, and indeed, it was a solid color with no alpha value (as others on SO have mentioned).
Much like so:

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <solid android:color="#ffffff" />
    </shape>
</code>```

It was after I added android:radius to this, and then the shadows were rendered.

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#ffffff" />
    <corners android:radius="1dp" />
</shape>
</code>```

And if you were wondering, why not set it to 0dp? Well, the shadows disappear again when the radius values were set to 0dp.

Body:
I'm trying to use Android Elevation to achieve the 'shadow' look for a view. The following is the layout xml:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.sample.app.Main2Activity">

    <LinearLayout
        android:layout_width="395dp"
        android:layout_height="match_parent"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:orientation="vertical"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:clipChildren="false">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="165dp"
            android:background="#FFFFFF"
            android:padding="30dp"
            android:layout_margin="30dp"
            android:elevation="10dp"
            android:text="TextView" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

This is how the layout looks:
Look ma, no shadows!

Any suggestions to fix this?

Body:
I'll get to the answer, but some background first. I was trying to achieve the look with a custom view that used a ConstraintLayout. This view would be used in another layout. I was when I tried using a simple TextView that I realised that the shadows weren't being rendered because, thus destroying my assumption that it was something ConstraintLayout related.

What worked?
I know, from the documentations, that shadows and rendered using a View's background. This, I have, and indeed, it was a solid color with no alpha value (as others on SO have mentioned).
Much like so:

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <solid android:color="#ffffff" />
    </shape>

It was after I added android:radius to this, and then the shadows were rendered.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#ffffff" />
    <corners android:radius="1dp" />
</shape>

And if you were wondering, why not set it to 0dp? Well, the shadows disappear again when the radius values were set to 0dp.


问:
Most efficient way to implement matrix functions?
I've been trying for a while to figure out the most efficient way of handling a two dimensional array (i.e. a matrix) that contains a variable.
I construct a large matrix by concatenating smaller arrays, weighted with a variable. As a simplified example, this is what I currently do.

```<code>function myMatrix(x::Float64)
    M = vcat(hcat(x*A, C), hcat(C, 2*x*B))
    return M
end

const A = ones(2,2)
const B = ones(2,2)
const C = zeros(2,2)
y_values = collect(0:0.01:10)

for y in y_values
    eivals, eivecs = eig(myMatrix(y))
    dosomething(eivals,eivecs)
end
</code>```

The problem: I have more (and more complex, non-diagonal) matrices and the final size is pretty large. At this moment, I call the function a few hundred times. Does anyone have a suggestion on what to do to make this process more efficient in terms of runtime?

Thanks in advance

答:
This solution, using preallocation as proposed somewhere in the comments, does not solve my problem directly (because of the way I construct the matrices) but it may still be useful for some people reading this. Also I don't guarantee for the initially used statement of "most efficient", as this seems to widely depend on your purposes, size of the matrices and so on. The method is also mentioned in the Performance Tips section of Julia.

Because there has been some confusion, consider the following example:

```<code>function myMatrix(x::Float64)
    M = vcat(hcat(x*A, C), hcat(D, 2*x*B))
    return M
end

function doSomething(A::Array{Float64,2})
    nothing
end

const ArraySize = 1000
const A = ones(ArraySize,ArraySize)
const B = ones(ArraySize,ArraySize)
const C = rand(ArraySize,ArraySize)
const D = rand(ArraySize,ArraySize)

for i = 1:1000
    ret = myMatrix( convert(Float64,i) )
    doSomething(ret)
end
</code>```

This does literally nothing but construct a BlockMatrix(function) from initial matrices depending on one parameter. I was thinking this repeated construction is redundant and indeed, one can preallocate the memory for the matrix by writing:

```<code>function xinc!(ret::Array{T,2}, x::T) where T
    ret[1:ArraySize, 1:ArraySize] = x*A
    ret[1:ArraySize, ArraySize+1:2*ArraySize] = C
    ret[ArraySize+1:2*ArraySize, 1:ArraySize] = D
    ret[ArraySize+1:2*ArraySize, ArraySize+1:2*ArraySize] = 2*x*B
    nothing
end

function doSomething(A::Array{Float64,2})
    nothing
end

const ArraySize = 1000
const A = ones(ArraySize,ArraySize)
const B = ones(ArraySize,ArraySize)
const C = rand(ArraySize,ArraySize)
const D = rand(ArraySize,ArraySize)

ret = Array{Float64}(2*ArraySize, 2*ArraySize)
for i = 1:1000
    xinc!(ret, convert(Float64,i))
    doSomething(ret)
end
</code>```

For me, the second code executes in 9.866s while the first takes up 38.076s.

Edit: In response to the previous comment, if i write

```<code>function xinc!(ret::Array{T,2}, x::T) where T
    ret = [x*A  C
            D   2*x*B]
    nothing
end
</code>```

the code takes 16.173s to execute. I don't know why, but this way of assigning the matrix is substantially slower.

Body:
I've been trying for a while to figure out the most efficient way of handling a two dimensional array (i.e. a matrix) that contains a variable.
I construct a large matrix by concatenating smaller arrays, weighted with a variable. As a simplified example, this is what I currently do.

function myMatrix(x::Float64)
    M = vcat(hcat(x*A, C), hcat(C, 2*x*B))
    return M
end

const A = ones(2,2)
const B = ones(2,2)
const C = zeros(2,2)
y_values = collect(0:0.01:10)

for y in y_values
    eivals, eivecs = eig(myMatrix(y))
    dosomething(eivals,eivecs)
end

The problem: I have more (and more complex, non-diagonal) matrices and the final size is pretty large. At this moment, I call the function a few hundred times. Does anyone have a suggestion on what to do to make this process more efficient in terms of runtime?

Thanks in advance

Body:
This solution, using preallocation as proposed somewhere in the comments, does not solve my problem directly (because of the way I construct the matrices) but it may still be useful for some people reading this. Also I don't guarantee for the initially used statement of "most efficient", as this seems to widely depend on your purposes, size of the matrices and so on. The method is also mentioned in the Performance Tips section of Julia.

Because there has been some confusion, consider the following example:

function myMatrix(x::Float64)
    M = vcat(hcat(x*A, C), hcat(D, 2*x*B))
    return M
end

function doSomething(A::Array{Float64,2})
    nothing
end

const ArraySize = 1000
const A = ones(ArraySize,ArraySize)
const B = ones(ArraySize,ArraySize)
const C = rand(ArraySize,ArraySize)
const D = rand(ArraySize,ArraySize)

for i = 1:1000
    ret = myMatrix( convert(Float64,i) )
    doSomething(ret)
end

This does literally nothing but construct a BlockMatrix(function) from initial matrices depending on one parameter. I was thinking this repeated construction is redundant and indeed, one can preallocate the memory for the matrix by writing:

function xinc!(ret::Array{T,2}, x::T) where T
    ret[1:ArraySize, 1:ArraySize] = x*A
    ret[1:ArraySize, ArraySize+1:2*ArraySize] = C
    ret[ArraySize+1:2*ArraySize, 1:ArraySize] = D
    ret[ArraySize+1:2*ArraySize, ArraySize+1:2*ArraySize] = 2*x*B
    nothing
end

function doSomething(A::Array{Float64,2})
    nothing
end

const ArraySize = 1000
const A = ones(ArraySize,ArraySize)
const B = ones(ArraySize,ArraySize)
const C = rand(ArraySize,ArraySize)
const D = rand(ArraySize,ArraySize)

ret = Array{Float64}(2*ArraySize, 2*ArraySize)
for i = 1:1000
    xinc!(ret, convert(Float64,i))
    doSomething(ret)
end

For me, the second code executes in 9.866s while the first takes up 38.076s.

Edit: In response to the previous comment, if i write

function xinc!(ret::Array{T,2}, x::T) where T
    ret = [x*A  C
            D   2*x*B]
    nothing
end

the code takes 16.173s to execute. I don't know why, but this way of assigning the matrix is substantially slower.


问:
Return array and show without iterating in laravel
I am sending array through the controller in compact.

```<code>    $medicines = Medicine::all()->pluck('medicine_name')->toArray();
    return view('orders.order',compact('medicines'));
</code>```

I want to display array in the blade without iterating,

output should be like $medicines = ['medicine1','medicine2','medicine3']

how to achieve it?

if I return $medicine variable I am getting the expected output how do I pass into the view?

答:
Try to implode the result first then assign that

```<code>$medicines = Medicine::all()->pluck('medicine_name')->toArray();
$medicines = implode(",",$medicines);
return view('orders.order',compact('medicines'));
</code>```

in your view add this code

```<code>{{ $medicines}}
</code>```

Body:
I am sending array through the controller in compact.

    $medicines = Medicine::all()->pluck('medicine_name')->toArray();
    return view('orders.order',compact('medicines'));

I want to display array in the blade without iterating,

output should be like $medicines = ['medicine1','medicine2','medicine3']

how to achieve it?

if I return $medicine variable I am getting the expected output how do I pass into the view?

Body:
Try to implode the result first then assign that

$medicines = Medicine::all()->pluck('medicine_name')->toArray();
$medicines = implode(",",$medicines);
return view('orders.order',compact('medicines'));

in your view add this code

{{ $medicines}}


问:
Combine two sets conditionally
I have a Person object which has a name attribute and some other attributes. I have two HashSet with Person objects. Note that name is not an unique attribute meaning that two Persons with same name can have different height so using HashSet does not guarantee that two Persons with same name are not in the same set.

I need to add one set to another so there are no Persons in the result with the same name. So something like this:

```<code>public void combine(HashSet<Person> set1, HashSet<Person> set2){
    for (String item2 : set2) {
        boolean exists = false;
        for (String item1 : set1) {
            if(item2.name.equals(item1.name)){
                exists = true;
            }
        }
        if(!exists){
            set1.add(item2);
        }
    }
}
</code>```

Is there a cleaner way of doing this in java8?

答:
If it makes sense for you to override equals and hashCode you can use something like this:

```<code>Set<Parent> result = Stream.concat(set1.stream(), set2.stream())
            .collect(Collectors.toSet());
</code>```

Without the Java 8 streams you can easily just do this:

```<code>Set<Parent> result = new HashSet<>();
result.addAll(set1);
result.addAll(set2);
</code>```

But remember this solution is only feasible when it makes sense to have equals and hashCode overridden.
 `

Title: Combine two sets conditionally

Body:
I have a Person object which has a name attribute and some other attributes. I have two HashSet with Person objects. Note that name is not an unique attribute meaning that two Persons with same name can have different height so using HashSet does not guarantee that two Persons with same name are not in the same set.

I need to add one set to another so there are no Persons in the result with the same name. So something like this:

public void combine(HashSet<Person> set1, HashSet<Person> set2){
    for (String item2 : set2) {
        boolean exists = false;
        for (String item1 : set1) {
            if(item2.name.equals(item1.name)){
                exists = true;
            }
        }
        if(!exists){
            set1.add(item2);
        }
    }
}

Is there a cleaner way of doing this in java8?

Body:
If it makes sense for you to override equals and hashCode you can use something like this:

Set<Parent> result = Stream.concat(set1.stream(), set2.stream())
            .collect(Collectors.toSet());

Without the Java 8 streams you can easily just do this:

Set<Parent> result = new HashSet<>();
result.addAll(set1);
result.addAll(set2);

But remember this solution is only feasible when it makes sense to have equals and hashCode overridden.
 `


问:
Can I use Visual Studio Snippets to generate SQL code
I want to use Visual Studio snippets to generate SQL code, for example we have standard naming conventions for foreign keys etc and it would be great if I could just expand a snippet in my SQL script file.

However as far as I can tell the only languages that are supported by the Snippet manager are C#, VB J# and XML

http://msdn.microsoft.com/en-gb/library/ms171421(VS.80).aspx

Does anyone know of a way to have a snippet expand to SQL?

Derek

答:
Visual Studio 2010 added support for SQL snippets.

You can read more about them at this MSDN page


问:
What response status code should I return?

I am having a simple shoppinglist app where users can create a shoppinglist, view a shopping list and even share a shopping list. My problem is given that a User has not created a shopping list lets say x but it has been created by another user and therefore it is in the database, what status code should I return to this User who didn't create this Shoppinglist? Should it be a 403 since it is in the database but this user has no permission to view it or should it be 404 since it does not exist in this user collection of shopping lists.

答:
While the accepted answer is perfectly fine, an alternative is to send 403 for every ID, even if it doesn't exist. That way there's no security hole either. I am assuming the user is identified through authentication and know that /lists/200 is theirs, therefore IDs up to 200 probably exist. If both /lists/50 and /lists/50000000 both return 403, the user is none the wiser.

This behaviour might be safer in the face of intermediaries like caching proxies, which can cache 404s publicly but not 403 responses.


问:
Icons at the bottom of the navbar not moving according to the resizing of the frame

I am trying to position something at the bottom of the navbar.

Sample code: https://jsfiddle.net/545cdqb2/1/

Having trouble with this part of the code.

```<code>.push-to-bottom
{
  position: absolute;
  bottom: 0px;
  height: 100px;
  width: 100%;
}
</code>```

Upon resizing of the frame, the "red div" hides the navbar elements behind it and I'm unable to click on them.

Issue screenshot

答:
Just use the flexbox system. I made a wrapper around the navbar and the red container. Remove the absolute positioning of the red box!

```<code>@media (min-width: 768px) {
    #navWrapper {
        height: 100vh;
        display: flex;
        flex-direction: column;
        justify-content: space-between
    }

    #navbar {
        flex-grow: 1;
    }
}

.push-to-bottom {
    height: 100px;
    width: 100%;
    flex-shrink: 0;
}
</code>```

With the flexbox system you can easily spare both containers (nav and red one) from each other if you give the navbar a flex-grow of 1. Wrap it in a media query for the non-mobile version or it will crush your design! The red box get a flex-shrink: 0 to keep its height of 100px!

The html code (important snippet)

```<code><div id="navWrapper" class="container">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a href="#">Brand Name</a>
    </div>
    <div id="navbar" class="navbar-collapse collapse">
        <ul class="nav navbar-nav navbar-font-family">
            <li><a href="#">Nav 1</a></li>
            <li><a href="#">Nav 2</a></li>
            <li><a href="#">Nav 3</a></li>
            <li><a href="#">Nav 4</a></li>
            <li><a href="#">Nav 5</a></li>
            <li><a href="#">Nav 6</a></li>
            <li><a href="#">Nav 7</a></li>
        </ul>
    </div>
    <div align="center" class="hidden-xs push-to-bottom" style="background-color: red; color: black">Hello!</div>
</div>
</code>```

Working Sample:
https://jsfiddle.net/545cdqb2/8/

Body:
I am trying to position something at the bottom of the navbar.

Sample code: https://jsfiddle.net/545cdqb2/1/

Having trouble with this part of the code.

.push-to-bottom
{
  position: absolute;
  bottom: 0px;
  height: 100px;
  width: 100%;
}

Upon resizing of the frame, the "red div" hides the navbar elements behind it and I'm unable to click on them.

Issue screenshot

Body:
Just use the flexbox system. I made a wrapper around the navbar and the red container. Remove the absolute positioning of the red box!

@media (min-width: 768px) {
    #navWrapper {
        height: 100vh;
        display: flex;
        flex-direction: column;
        justify-content: space-between
    }

    #navbar {
        flex-grow: 1;
    }
}

.push-to-bottom {
    height: 100px;
    width: 100%;
    flex-shrink: 0;
}

With the flexbox system you can easily spare both containers (nav and red one) from each other if you give the navbar a flex-grow of 1. Wrap it in a media query for the non-mobile version or it will crush your design! The red box get a flex-shrink: 0 to keep its height of 100px!

The html code (important snippet)

<div id="navWrapper" class="container">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a href="#">Brand Name</a>
    </div>
    <div id="navbar" class="navbar-collapse collapse">
        <ul class="nav navbar-nav navbar-font-family">
            <li><a href="#">Nav 1</a></li>
            <li><a href="#">Nav 2</a></li>
            <li><a href="#">Nav 3</a></li>
            <li><a href="#">Nav 4</a></li>
            <li><a href="#">Nav 5</a></li>
            <li><a href="#">Nav 6</a></li>
            <li><a href="#">Nav 7</a></li>
        </ul>
    </div>
    <div align="center" class="hidden-xs push-to-bottom" style="background-color: red; color: black">Hello!</div>
</div>

Working Sample:
https://jsfiddle.net/545cdqb2/8/


答:
If you want just output you can try as

```<code><?php echo "\$medicines = ['".implode("','",$medicines)."']"; ?>
</code>```

Here is Live demo : https://eval.in/915767

Title: Return array and show without iterating in laravel

Body:
If you want just output you can try as

<?php echo "\$medicines = ['".implode("','",$medicines)."']"; ?>

Here is Live demo : https://eval.in/915767


问:
Run an emulator on an AMD processor
I have created an emulator with Google API of API 25 in Android Studio and my machine has AMD Processor. Can I run the emulator?

答:
On AMD processor you may be run ARM architecture Android Image not Intel but
emulator become very slow.

better way

use Genymotion emulator for personal use, This work on both
Intel VT-X  and AMD-V technology.

Title: Run an emulator on an AMD processor


问:
Getting value from firebase returns error

Problem

With a social media app created by React Native I am trying to use a snapshot function to get data off of my firebase server, then add 1 to that value, then update that value on the server. The code I am doing that with is:

```<code>    this.setState({
      comments: firebase.database().ref('posts/'+this.state.passKey).once('value', function(snapshot) {snapshot.val().comments})
        })

    firebase.database().ref('posts').child(this.state.passKey).update({
      comments: this.state.comments+1
        })
</code>```

When I run this code though, I get an error, saying:

```<code>Reference.update failed:
First argument contains NaN in property 'posts.randompostkey.comments'
</code>```

My Server

答:
What you need to use is a transaction.

```<code>postRef.transaction(function (post) {
            if (post) {
                    post.commentCount++;
                }
            }
            return post;
        });
</code>```

This way you can get your data, update the value and then post it back in a secure way, ensuring it is not being updated simultaneously by someone else

Body:
Problem

With a social media app created by React Native I am trying to use a snapshot function to get data off of my firebase server, then add 1 to that value, then update that value on the server. The code I am doing that with is:

    this.setState({
      comments: firebase.database().ref('posts/'+this.state.passKey).once('value', function(snapshot) {snapshot.val().comments})
        })

    firebase.database().ref('posts').child(this.state.passKey).update({
      comments: this.state.comments+1
        })

When I run this code though, I get an error, saying:

Reference.update failed:
First argument contains NaN in property 'posts.randompostkey.comments'

My Server

Body:
What you need to use is a transaction.

postRef.transaction(function (post) {
            if (post) {
                    post.commentCount++;
                }
            }
            return post;
        });

This way you can get your data, update the value and then post it back in a secure way, ensuring it is not being updated simultaneously by someone else