What is the name of the new ubuntu font?

Question: I've upgraded from 10.04 to 10.10 and so much of my preferences are set as they where in 10.04. I haven't seen much difference in the fonts used by ubuntu, do they have a different name? Which is it?
Answer: It's called the Ubuntu Font Family
In the UI  for the font menu it shows up as just "Ubuntu"
Comment: The "Liberation Mono" font is also a great choice for the "Fixed width font" setting.
Comment: Of course, if you're using 11.10 or later then "Ubuntu Mono" (which is part of the Ubuntu Font Family) is the best choice of all, and set by default. ;)
Comment: Couldn't resist commenting:"Dejavu Sans Mono" is also great for use as the "Fixed width font".


Is there a way to overwrite text with different text using HTML, CSS etc?

Question: Not sure if this is a stupid question or not.
Is there any way to overwrite text in HTML/CSS with a different text?
An example of what I mean

I want to make it obvious it's a terrible reskin of a previous website.
I know I could do it with an image, but I'd like to have it as regular text. Is it something you'd have to do with custom fonts? Or is it even possible?
Answer: This is a very basic example to achieve this.
The content that you really want to display is in the :after of the span that surrounds the year.

body {
  background: #000;
}

h1 {
  color: #fff;
  font-family: sans-serif;
}

.year {
  position: relative;
}

.year:after {
  position: absolute;
  top: .1rem;
  left: 0;
  display: block;
  content: '2021';
  transform: rotate(-10deg);
  color: red;
  font-family: 'Comic Sans MS';
}

Happy 2020 anniversary!


How do I set up CORS correctly on a Jooby application

Question: I am creating an API with the Jooby framework mostly following this guide. I am also using Vue.js as the frontend. However I am having issues with CORS. When I try to do a get request from my Vue.js frontend I get the error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.
This is my Jooby application.conf file:
# add or override properties
# See https://github.com/typesafehub/config/blob/master/HOCON.md for more
details
db = mem

schema = """

create table if not exists pets (

id int not null auto_increment,

name varchar(255) not null,

primary key (id)

);
"""
cors {
# Configures the Access-Control-Allow-Origin CORS header. Possibly values:
*, domain, regex or a list of previous values.
# Example:
# "*"
# ["http://foo.com"]
# ["http://*.com"]
# ["http://foo.com", "http://bar.com"]
origin: "*"

# If true, set the Access-Control-Allow-Credentials header
credentials: true

# Allowed methods: Set the Access-Control-Allow-Methods header
allowedMethods: [GET, POST]

# Allowed headers: set the Access-Control-Allow-Headers header. Possibly
values: *, header name or a list of previous values.
# Examples
# "*"
# Custom-Header
# [Header-1, Header-2]
allowedHeaders: ["X-Requested-With, Content-Type, Accept, Origin"]

# Preflight max age: number of seconds that preflight requests can be cached
by the client
maxAge: 30m

# Set the Access-Control-Expose-Headers header
# exposedHeaders: []
}

And this is App.java file where I query the database
package org.jooby.guides;

import java.util.List;

import org.jooby.Jooby;
import org.jooby.Results;
import org.jooby.jdbc.Jdbc;
import org.jooby.jdbi.Jdbi;
import org.jooby.json.Jackson;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;

import com.typesafe.config.Config;

public class App extends Jooby {

{
use(new Jackson());

use(new Jdbc());

use(new Jdbi()
    // 1 dbi ready
    .doWith((final DBI dbi, final Config conf) -> {
      // 2 open a new handle
      try (Handle handle = dbi.open()) {
        // 3. execute script
        handle.execute(conf.getString("schema"));
      }
    }));

/** Pet API. */
use("/api/pets")
    /** List pets. */
    .get(req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        PetRepository repo = handle.attach(PetRepository.class);
        List<Pet> pets = repo.list();
        return pets;
      });
    })
    /** Get a pet by ID. */
    .get("/:id", req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        int id = req.param("id").intValue();

        PetRepository repo = handle.attach(PetRepository.class);
        Pet pet = repo.findById(id);
        return pet;
      });
    })
    /** Create a pet. */
    .post(req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        // read from HTTP body
        Pet pet = req.body(Pet.class);

        PetRepository repo = handle.attach(PetRepository.class);
        int petId = repo.insert(pet);
        pet.setId(petId);
        return pet;
      });
    })
    /** Update a pet. */
    .put(req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        // read from HTTP body
        Pet pet = req.body(Pet.class);

        PetRepository repo = handle.attach(PetRepository.class);
        repo.update(pet);
        return pet;
      });
    })
    /** Delete a pet by ID. */
    .delete("/:id", req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        int id = req.param("id").intValue();

        PetRepository repo = handle.attach(PetRepository.class);
        repo.deleteById(id);
        return Results.noContent();
      });
    });
}

public static void main(final String[] args) {
run(App::new, args);
}

}

How do I fix this?
Comment: I think you will have to add `Access-Control-Allow-Origin` in `allowedHeaders` property
Answer: From documentation you need to add a CorsHandler:
{
   use("*", new CorsHandler());
   ...
}

Properties are optional, unless you want to change a default value.
Answer: You can manually specify the header and the accept method (Jooby MVC)
Cors cors = new Cors()
                .withHeaders("Content-Type", "Accept", "Origin","Authorization")
                .withMethods("GET", "POST", "OPTIONS", "PUT", "DELETE");
pluginApp.use("*", new CorsHandler(cors));


Can I use a wood top plate on top of a steel track to build a roof-bearing steel frame?

Question: I am building a room within my garage using double studs, double track, steel framing.  The outer dimensions for this room are 23' l x 16' 6" w x 10' h, and will share no common walls or ceiling with the garage space.  The garage floor is 6" thick concrete.
Most steel construction calls for attaching the tracks to existing floor / ceiling joists, and then place the studs in between the two tracks.  This will not work for my application, as I have no ceiling joists to attach to (so the top track will be flimsy).
To solve this problem, I would like to use a wood top plate on top of a steel track, and build a flat roof on top of the wooden top plate.  (Similar to Detail No. W1 (p60) from the HUD: Hybrid Wood and Steel Details-Builder's Guide document.)  The "Data" on page 61 of the guide lead me to believe this approach is possible.
My concern is that I have not found any examples of this kind of construction from searching the internet.
Questions:

Does adding a wood top plate on top of the steel top track provide enough weight to stabilize the wall?

Are there any resources showing a build detail of this kind of construction?
Comment: Why the composite material construction process...especially where you live? What's the fascination with using steel and wood?
Comment: The steel is for wall soundproofing.  The wood is for ease of roof framing / obtaining materials in the span length I'm planning to use.
Comment: Does that mean that you are essentially building a freestanding structure inside your garage? Is there a reason to think that a steel top plate is not appropriate for the trusses Required?
Answer: We design from the top down and build from the bottom up. I've learned that staying with "standard building techniques" in both the design and construction phases will save time and money.
We design custom homes and when we use a product that's never been shipped west of the Mississippi, then we'll pay extra for that particular product and pay extra for the labor to prep and install, because the local contractors are not familiar with that product.
Likewise, if we design a 12' diameter curved wall in the house, we'd better have a good reason, because that wall will cost extra.
Likewise, if you design a composite wall construction detail, you'd better have a good reason because you're going to pay extra.
Standard building practices tend to use either steel or wood, but not combined because they are not familiar to 1) codes review technicians, 2) building inspectors, 3) sub-contractors who will need to adjust their products to fit the new technique, and 4) General Contractors who will need to coordinate scheduling, miscellaneous materials to finish installations, etc.
There are some issues with your assumptions. Steel construction does NOT make rooms more or less soundproof. (Staggered stud construction, double wall construction, types of materials used on and in the wall, etc. all help with sound control.) Steel construction (non-combustible construction) is for better fire resistance, not better soundproofing.
Summary:
There's a reason that you're not finding "typical" construction "details" (as you call it) because it's not done often or frequently. Mixing construction systems will increase costs and may eliminate some contractors from participating.


How can I do this pandas lookup with a series?

Question: I have a Series S:
                               attr
first   last       visit
andrew  alexander  baseline    abc
andrew  alexander  followup    abc
bruce   alexander  baseline    abc
bruce   alexander  followup    xyz
fuzzy   dunlop     baseline    xyz
fuzzy   dunlop     followup    abc

and a DataFrame df:
                               abc   xyz
first   last       visit
andrew  alexander  baseline    1     7
andrew  alexander  followup    2     8
bruce   alexander  baseline    3     9
bruce   alexander  followup    4     10
fuzzy   dunlop     baseline    5     11
fuzzy   dunlop     followup    6     12

How can I get a new series S2, where for each index in S, the value is selected from df. If I was to use a loop, I'd do it this way:
lookup = pd.Series(index=S.index)
for ix, attr in S.iteritems():
    lookup.loc[ix] = df.loc[ix, attr]

Is there a more direct way to do this with a pandas function?
The result should look like this:
first   last       visit
andrew  alexander  baseline    1
andrew  alexander  followup    2
bruce   alexander  baseline    3
bruce   alexander  followup    10
fuzzy   dunlop     baseline    11
fuzzy   dunlop     followup    6

Comment: Aside: the representation of your series S makes it look more like a 1-column dataframe than a series.
Comment: Ah oops - that's what I get for writing that in a text editor instead of a python console :-}
Answer: IIUC, you can use DataFrame.lookup():
In [7]: pd.Series(df.lookup(s.index, s['attr']), index=df.index)
Out[7]:
first   last       visit
andrew  alexander  baseline     1
                   followup     2
bruce   alexander  baseline     3
                   followup    10
fuzzy   dunlop     baseline    11
                   followup     6
dtype: int64

if s is Series (not a DataFrame):
In [10]: pd.Series(df.lookup(s.index, s), index=df.index)
Out[10]:
first   last       visit
andrew  alexander  baseline     1
                   followup     2
bruce   alexander  baseline     3
                   followup    10
fuzzy   dunlop     baseline    11
                   followup     6
dtype: int64

Comment: @cᴏʟᴅsᴘᴇᴇᴅ, please undelete your answer - we did it at the same time :)
Comment: Hmmph.  This'll teach me to add comments to other people's answers, cost me valuable seconds. :-P
Comment: Note that if s is really a series, the `s['attr']` will fail, I think.
Comment: Sorry, you got it. I'll remove mine.
Comment: @DSM, yeah, that's true :-D
Comment: @DSM, yes, thank you. In OPs example `s` looks like a DF, that's why I did it this way...


php displaying image from stored path?

Question: UPDATE.
I can only display the images inside a query e.g.
if($Result = mysqli_query($Link, $Query)){
while($row = mysqli_fetch_array($Result))
{
$img = $row['path'];
echo '';
}
}

I want to display them inside a table but this code doesn't work :
<?php echo ''; ?>

BELOW ISSUE RESOLVED  :
I have images stored in a folder (uploads) and the path is stored in a database table in a field named path. I am trying to display the stored images.
$Link = mysqli_connect($Host, $User, $Password, $Database);
$Query = "SELECT * FROM $images";

if($Result = mysqli_query($Link, $Query)){
while($row = mysqli_fetch_array($Result))
{
$img = "uploads/" . $_FILES["file"]["name"];
echo '';
}
}

Comment: You need to be using `$row` instead of `$_FILES`
Answer: Your folder permissions for "uploads/" might not be set to public read.  Have you checked those already?  What is the URL that is output for your image?  Have you tried Copying URL and linked directly to it from your browser?  If the URL is coming back blank, try $row instead of $_FILES since you are just wanting the path to the file.
Comment: Thanks for the reply. Permissions are set to 777. If I type the full url in a browser the image is displayed.
Comment: @RazvanZ I cannot display the images inside HTML - I want to display them inside a table but this code doesn't work.

'; ?>
Answer: This line is wrong: $img = "uploads/" . $_FILES["file"]["name"];.
Replace it with $img = "uploads/" . $row[x]; where x is the number of column where file name is
OR
with $img = "uploads/" . $row['columnname'];. Here you have to replace columnname.
Comment: Thanks. Made the changes and noticed in firebird it was linking to the uploads directory twice i.e. uploads/uploads. Works with this :

$img = $row['path'];

php displaying image from stored path?


creating a loop to convert rolling date periods to as.Date

Question: I'm new to R, but have been following a pretty good guide to help along the way.
I've imported sales data for the past 36 months, used tidyr to move the Date columns to rows, and then cleaned the Date character string to a Month Date, Year.
My ask is this: I need to update this file every month and will have a new, rolling 36 month period. Is there an improvement to the function I created to automate the new periods (ex. Current 36 month period starts September 1, 2013, Next 36 month period starts October 1, 2013, etc.).
Any ideas on how to do this without having to cut and paste?
Below is my code
# import rolling periods
rolling <- read.csv("h:/R/BI with R/Rolling Periods.csv", header=T)

# remove last four columns
rolling <- rolling[,-c(42:45)]

# gather columns to rows with tidyr
require(tidyr)
rolling <- gather(rolling, "Date", "CSE", 6:41)

head(rolling)

# list from Date column
unique(rolling$Date)

# clean Date variable
clean = function(col) {
  col = gsub('X1.Month.9.1.2013.thru.9.30.2013..Case.Equivs', 'September 1, 2013', col, fixed = TRUE)
  col = gsub('X1.Month.10.1.2013.thru.10.31.2013..Case.Equivs', 'October 1, 2013', col, fixed = TRUE)
  col = gsub('X1.Month.11.1.2013.thru.11.30.2013..Case.Equivs', 'November 1, 2013', col, fixed = TRUE)
  col = gsub('X1.Month.12.1.2013.thru.12.31.2013..Case.Equivs', 'December 1, 2013', col, fixed = TRUE)
  col = gsub('X1.Month.1.1.2014.thru.1.31.2014..Case.Equivs', 'January 1, 2014', col, fixed = TRUE)
  col = gsub('X1.Month.2.1.2014.thru.2.28.2014..Case.Equivs', 'February 1, 2014', col, fixed = TRUE)
  col = gsub('X1.Month.3.1.2014.thru.3.31.2014..Case.Equivs', 'March 1, 2014', col, fixed = TRUE)
  col = gsub('X1.Month.4.1.2014.thru.4.30.2014..Case.Equivs', 'April 1, 2014', col, fixed = TRUE)
  col = gsub('X1.Month.5.1.2014.thru.5.31.2014..Case.Equivs', 'May 1, 2014', col, fixed = TRUE)
  col = gsub('X1.Month.6.1.2014.thru.6.30.2014..Case.Equivs', 'June 1, 2014', col, fixed = TRUE)
  col = gsub('X1.Month.7.1.2014.thru.7.31.2014..Case.Equivs', 'July 1, 2014', col, fixed = TRUE)
  col = gsub('X1.Month.8.1.2014.thru.8.31.2014..Case.Equivs', 'August 1, 2014', col, fixed = TRUE)
  col = gsub('X1.Month.9.1.2014.thru.9.30.2014..Case.Equivs', 'September 1, 2014', col, fixed = TRUE)
  col = gsub('X1.Month.10.1.2014.thru.10.31.2014..Case.Equivs', 'October 1, 2014', col, fixed = TRUE)
  col = gsub('X1.Month.11.1.2014.thru.11.30.2014..Case.Equivs', 'November 1, 2014', col, fixed = TRUE)
  col = gsub('X1.Month.12.1.2014.thru.12.31.2014..Case.Equivs', 'December 1, 2014', col, fixed = TRUE)
  col = gsub('X1.Month.1.1.2015.thru.1.31.2015..Case.Equivs', 'January 1, 2015', col, fixed = TRUE)
  col = gsub('X1.Month.2.1.2015.thru.2.28.2015..Case.Equivs', 'February 1, 2015', col, fixed = TRUE)
  col = gsub('X1.Month.3.1.2015.thru.3.31.2015..Case.Equivs', 'March 1, 2015', col, fixed = TRUE)
  col = gsub('X1.Month.4.1.2015.thru.4.30.2015..Case.Equivs', 'April 1, 2015', col, fixed = TRUE)
  col = gsub('X1.Month.5.1.2015.thru.5.31.2015..Case.Equivs', 'May 1, 2015', col, fixed = TRUE)
  col = gsub('X1.Month.6.1.2015.thru.6.30.2015..Case.Equivs', 'June 1, 2015', col, fixed = TRUE)
  col = gsub('X1.Month.7.1.2015.thru.7.31.2015..Case.Equivs', 'July 1, 2015', col, fixed = TRUE)
  col = gsub('X1.Month.8.1.2015.thru.8.31.2015..Case.Equivs', 'August 1, 2015', col, fixed = TRUE)
  col = gsub('X1.Month.9.1.2015.thru.9.30.2015..Case.Equivs', 'September 1, 2015', col, fixed = TRUE)
  col = gsub('X1.Month.10.1.2015.thru.10.31.2015..Case.Equivs', 'October 1, 2015', col, fixed = TRUE)
  col = gsub('X1.Month.11.1.2015.thru.11.30.2015..Case.Equivs', 'November 1, 2015', col, fixed = TRUE)
  col = gsub('X1.Month.12.1.2015.thru.12.31.2015..Case.Equivs', 'December 1, 2015', col, fixed = TRUE)
  col = gsub('X1.Month.1.1.2016.thru.1.31.2016..Case.Equivs', 'January 1, 2016', col, fixed = TRUE)
  col = gsub('X1.Month.2.1.2016.thru.2.28.2016..Case.Equivs', 'February 1, 2016', col, fixed = TRUE)
  col = gsub('X1.Month.3.1.2016.thru.3.31.2016..Case.Equivs', 'March 1, 2016', col, fixed = TRUE)
  col = gsub('X1.Month.4.1.2016.thru.4.30.2016..Case.Equivs', 'April 1, 2016', col, fixed = TRUE)
  col = gsub('X1.Month.5.1.2016.thru.5.31.2016..Case.Equivs', 'May 1, 2016', col, fixed = TRUE)
  col = gsub('X1.Month.6.1.2016.thru.6.30.2016..Case.Equivs', 'June 1, 2016', col, fixed = TRUE)
  col = gsub('X1.Month.7.1.2016.thru.7.31.2016..Case.Equivs', 'July 1, 2016', col, fixed = TRUE)
  col = gsub('X1.Month.8.1.2016.thru.8.31.2016..Case.Equivs', 'August 1, 2016', col, fixed = TRUE)
  return(col)
}

rolling$Date = clean(rolling$Date)
head(rolling)

# convert to Date object
rolling$Date = as.Date(rolling$Date, format="%B %d, %Y")
head(rolling)

Comment: Parse the date: `rolling$Date_clean <- as.Date(rolling$Date, 'X1.Month.%m.%d.%Y')`. You can then use `format(rolling$Date_clean, '%B%e, %Y')` if you _really_ need a character date.
Answer: Convert the column to a data frame using dot as the field separator and then
format using sprintf and month.name like this:
clean2 <- function(x) {
  DF <- read.table(text = x, sep = ".")
  with(DF, sprintf("%s %d, %d", month.name[V3], V4, V5))
}

The last statement could alternately have been written as:
with(DF, format(as.Date(paste(V5, V3, V4, sep = "-")), "%B %e, %Y"))

example
For example, using the input in the Note below:
clean2(x)
## [1] "September 1, 2013" "October 1, 2013"   "November 1, 2013"

Note: Here is some sample data in reproducible form:
x <- c("X1.Month.9.1.2013.thru.9.30.2013..Case.Equivs",
       "X1.Month.10.1.2013.thru.10.31.2013..Case.Equivs",
       "X1.Month.11.1.2013.thru.11.30.2013..Case.Equivs")

Answer: It seems you are only looking at the first part of your rolling date to determine the representative date (the date you are replacing).
In that case you could take advantage of backreferences in replacement when using gsub and regular expression
# Function might not be need now
clean  <- function(col) {
    col <- gsub("X1\\.Month\\.(\\d{1,2})\\.(\\d{1,2})\\.(\\d{4}).thru.*","\\1 \\2 \\3", col)
}

head(rolling)

# convert to Date object
#Note the new date fomat
rolling$Date <- as.Date(rolling$Date, format="%m %d %Y")
head(rolling)

If you also need the ending date of the rolling date, you could still use more backreferences to capture the end date.


Range of number systems

Question:
I don't understand how to get the fraction part. This is what I came up with for the integer part.
A) For 12 bit unsigned = 0 to 4095
B) For 12 bit signed = -2048 to 2047
C) For 12 bit in 2's complement -4096 to 4095
Hopefully someone can explain the fraction part, thanks!
Comment: What do *you* think, and why?
Comment: For the fraction part it would be something like .5^(-12) ?
Answer: Fixed point means that fractional values are multiplied with some fixed scaling factor, and the result is stored as an integer (after truncation or rounding). In other words, to get the true value, you interpret the stores value as an integer and multiply it with the inverse of the scaling factor. Usually, the scaling factor is a power of the whatever base you pick for representing integers. The exponent then tells you how many fractional digits are preserved by this transform.
In the case of (a), that means that fractional values are multiplied with $2^{12}$, and the result is stores as an 24-bit integer. To get the actual value back, you thus need to multiply the stored integer with $2^-{12}$. The largest possible value that can yield is $(2^{24}-1)2^{-12} = 2^{12} - 2^{-12}$. The smallest value is, unsurprisingly, $0\cdot 2^{-12} = 0$.
In the case of (b), the (signed!) integer is stored as one sign bit plus 23 magnitude bits, the scaling factor is again $2^{12}$, since it can store 12 fractional digits. The maximum value the integer can take is $(2^{23}-1)$, which corresponds to an actual value of $2^{11} - 2^{-12}$. The minimal value is $-(2^{11} - 2^{-12}) = -2^{11} + 2^{-12}$, since the minimum value the integer can take is $-(2^{23}-1)$.
I'll leave (c) to you.

You can also view this in another way. Fractional values work in the binary system just as they do in the decimal system - the first digit to the right of the "decimal" point has weight $\frac{1}{2}$, the next one $\frac{1}{4}$ and so on.
Thus, if as in the case of (a) you have 12 digits to the left of the "decimal" point and 12 to the right, and if all these digts are $1$, the value is $$
  \underbrace{2^{11} + 2^{10} + \ldots + 2^0}_{=2^{12}-1} + \underbrace{2^{-1} + \ldots 2^{-12}}_{=1 - 2^{-12}} =  2^{12} - 2^{-12}
$$
Since all weights are positive, that must be the largest representable number - if any bit was zero, you'd add fewer values, so the result would surely be smaller.
In the case of (b), you only have 11 digits to the left of the decimal point, and now the weights are either positive (if the sign bit is $0$), or all negative (if the sign bits is $1$). You thus get the smallest number by setting all bits to $1$, and the resulting value is $$
  \underbrace{-2^{10} - 2^{10} - \ldots - 2^0}_{=-(2^{11}-1)} + \underbrace{-2^{-1} - \ldots 2^{-12}}_{=-(1 - 2^{-12})} =  -2^{11} + 2^{-12}
$$
Comment: Thank you for taking the time to explain the stuff. If you can add something for the 2's complement, maybe that would be helpful for future visitors. Thanks again!
Comment: @Ammar Please feel free to edit my answer and include a discussion of how this works for $2"'s complements. Or alternative, you can add your own answer explaining that.

Range of number systems


Disable dictation feature Ctrl+D

Question: When I press Ctrl+D I get this dictation-like mic in my screen:

I would like to disable this shortcut, because I need it in the terminal for other applications.
However, I can not find the shortcut in the keyboard settings, or anywhere else.
Comment: This looks shockingly like Mac OS X. If it actually is Mac, the kind people over on [apple.SE] will be able to help much better than us.
Comment: What Ubuntu version and flavour are you using?
Answer: You can use this command to disable the action:
trap "" 3

To go back to default you should use:
trap " " 3

In this example date is called when you press Ctrl+D:
trap "date" 3

kill -l gives you a list of signals.

Disable dictation feature Ctrl+D


"firebase" is added as a dependency in your project's package.json but it doesn't seem to be installed

Question: "firebase" is added as a dependency in your project's package.json but it doesn't seem to be installed. Please run "yarn" or "npm install" to fix this issue.
I am getting this error while running react-native on expo-cli locally. I have firebase-7.9.0 and expo- ^40.0.0 in my dependencies still it is showing this error.
Comment: did you run `yarn` or `npm install` after adding it as dependency?
Comment: This refers to same problem and contains possible some solutions: https://giters.com/expo/expo-cli/issues/3781?amp=1
Answer: If you are using expo, you are supposed to install firebase using expo.

expo install firebase
Answer: I added @ before firebase and the build worked.
"dependencies": {
    "expo": "~41.0.1",
    "@firebase": "^9.0.0-beta.2",
    ...
  },

Comment: Although it's not to spec, this is the only solution that has worked thus far. I have no idea how you arrived at this but this hack works until another solution is suggested!
Note: this breaks following npm installs so you have to remove the "@" prior to running it.
Comment: I'm having the same issue with an Expo managed app:

Changing the dependency from ```"firebase": "^9.0.2",``` to ```"@firebase": "^9.0.2",``` or ```"firebase9": "^9.0.2",```
solves the issue when running the app.
But whenever I need to install a new package, I need to switch back to ```"firebase": "^9.0.2",``` otherwise yarn gets confused. Any ideas of a workaround that?
Comment: This is not valid. Please refer to the [package.json specifications](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#dependencies). Also, the dependencies are not the problem.
Comment: @Shivam welp, it worked when deleting the cache and package.lock didn't ¯\_(ツ)_/¯
Comment: It would work without the `@` though. You should not really use out-of-spec things like this.
Comment: Can't see how this would work reliably, pointing at the `@firebase` folder likely only works if you're not using any `/compat` imports as that's under the `firebase` folder
Comment: This also works here, as I need a version greater than Expo one. Any better solution than waiting for Expo 43?


REST annotations injection together with injection of custom XML objects in one request

Question: 1)
I'm dealing with similar situation like at How can I pass complex objects as arguments to a RESTful service? , but actually the injection of my custom XML objects if injected all right, IF i do not annotate method parameter with @Form.
This is wrapper request object to injection:
<code>@XmlRootElement(name = "request")
@XmlAccessorType(XmlAccessType.NONE)
@XmlType
@Consumes({"application/xml", "application/json"})
public class TestRequest {
    @PathParam(value = "value")
    private String value;  // this is injected only when @Form param is added to the method parameter definition

    @XmlElement(type = Test.class)
    private Test test; // this is XML object I want to inject from the REST request

    @XmlElement
    private String text; // or inject other XML element like this
}
</code>
So this would inject me REST parameters (e.g. {value} - @PathParam("value") annotated in TestRequest).
BUT this doesn't unmarshall the XML object Test in wrapper object TestRequested.
<code>@POST
@Path("tests/{value}")
@Consumes("application/xml")
@Produces("application/xml")
public void addTest(**@Form** TestRequest req);
</code>
And following definition would inject only the XML object Test but doesn't inject the REST annotations (e.g. {value} from URI):
<code>public void addTest(TestRequest req);  // without @Form annotation now
</code>
2) I also tried another approach by catching request to custom MessageBodyReader implementation but have been lost in the details where to find code, method or class of JAX-RS or RESTEasy that actually does this parsing/injecting of REST annotations(@PathParam, @QueryParam,...).
I also noticed that when there is @Form annotation in method definition, then custom MessageBodyReader isn't even catched (propably built-in one for REST parameters catches that request and custom reader is then ignored).
I could in this custom message body reader solution somehow call that built-in injection provider but i didn't find suitable documentation and it seems I'm doing something wrong and all can be done more simplier some other way.

To summarise the goal: inject both REST parameters (@PathParam, @QueryParam etc.) and custom XML/JSON objects somehow in one request in ONE wrapper object.
(It works with one wrapper object annotated @Form and the other parameter to be without @Form annotation, but I would like to have all in one wrapper object).
Thank you for any insights or help.
Answer: You are mixing JAX-RS and JAXB annotations. That's a bad idea. Use JAX-RS annotations on resource classes and JAXB annotations on represenation classes.
Comment: So there isn't any way to have only one parameter on WS method, so everything about request can be injected to some custom class?


What options do I have for quick disconnects for copper/plumbing?

Question: (Related to this question) but I think that may be too specific in that I already had an idea of how to solve the problem - perhaps the better way is to pose the problem and ask for the best solutions:
PROBLEM:
I have a tank of fluid that has to get connected to a movable set of copper pipes/tubes.  I will be connecting and disconnecting a few times per year to clean, etc.
The fluid going through the system will be for food use (maple sap turned into maple syrup)
What is the best way to allow connections to be taken on and off and keep food quality integrity and connect copper pipes together?
The temperature of the fluid will reach (potentially) 180F and I want no leaching of plastic or vinyl, etc.
Answer: You might want to take a look at what micro-breweries use.  The connections between the various tanks are fairly modular, allowing the wort to be pumped out of the mash tun, through a heat exchanger, and into the holding vessels.  From what I've seen, the pipes have flanges that are held together by a circular clamp.
Answer: For a really quick disconnects, use all-brass garden hose quick couplers.
For occasional disconnects, use  brass/copper unions.
Answer: Maybe you can look at Compression fittings for copper pipes (see here for instance).
Comment: These might be OK, but they're not particularly easy to remove.


Run .NET 2.0 applications for Win

Question: I am trying to run application for Windows on Ubuntu 11.10
I tried
wine /path/to/file.exe

Error is:
wine: Install Mono for Windows to run .NET 2.0 applications.

I  have mono(seems to be not Mono for windows)
mono /path/to/file.exe

gives me error:
The assembly mscorlib.dll was not found or could not be loaded.
It should have been installed in the `/usr/lib/mono/2.0/mscorlib.dll' directory.

What do I need to do?
Answer: I had a similar problem on 12.04, and this is what i did:
sudo apt-get install mono-complete

and then
mono /path/to/file.exe

that's it!
Answer: try installing mono for windows or try .NET for windows with winetricks. In a shell try:
winetricks dotnet20

and
winetricks mono28

Comment: Got this error:
`fixme:advapi:DecryptFileA "C:\\users\\yasin\\Temp\\IXP000.TMP\\" 00000000
fixme:advapi:LsaOpenPolicy ((null),0x33f31c,0x00000001,0x33f344) stub
fixme:advapi:LsaClose (0xcafe) stub
fixme:storage:create_storagefile Storage share mode not implemented.
err:seh:raise_exception Unhandled exception code c0000005 flags 0 addr 0x451d7c`
@Andrei: who cares about what you want? The OP wants wine.
Comment: Error: Cannot install on a 64-bit operating system.
Comment: I found the fix to my 64bit problem and was ready to write it in an answer, BUT THIS QUESTION IS PROTECTED...
Comment: Fixed this error above by deleting `~/.wine directory`.
Comment: "This product is not supported on a 64-bit operating system."
Answer: In my case, I found that installing mono-complete did not allow my application (CloudBerry Explorer) to function, as it was looking for configuration files that running via Mono did not properly find.
I'm running on a x64 system, which .NET 2.0 won't install on (see http://appdb.winehq.org/objectManager.php?sClass=version&iId=3754), so I found that I had to remove my wine directory and do:
export WINEARCH="win32"
winetricks dotnet20

(Alternatively, you could set a different WINEPREFIX for the application with a win32  architecture, but I had no need for that kind of separation of environments, and nuking my previous setup was perfectly acceptable.)
At this point I wanted to run winetricks mono28 but winetricks has not yet been updated to account for Novell removing the file from their mirror (see http://code.google.com/p/winetricks/issues/detail?id=221). I used the proposed solution in the ticket:
wget http://download.mono-project.com/archive/2.8/windows-installer/9/mono-2.8-gtksharp-2.12.10-win32-9.exe
wine mono-2.8-gtksharp-2.12.10-win32-9.exe

(This took about 30 minutes to download as the mono-project.com servers do not have the same kind of juice that Novell had, sadly...) It allowed the application I wanted to use to run (it has some issues but I think that's more about Wine support than it is the .NET support).
Comment: Wow, 2-years later and winetricks still hasn't been updated. Is winetricks abandoned?
Answer: Mono for Wine can be installed via apt:
sudo apt-get install wine-mono4.5.6\*

which would provide MS .NET compatibility compatibility layer.
See Mono page at Wine for more details.

Run .NET 2.0 applications for Win


How to display nested routes in different pages using React Hooks..?

Question: React Routing V5 --
Hi, In this Nested react routing, I want to display the 2nd nesting inside Resources page separately when i click the corresponding links. Right now it's displaying inside the Products Id page. Also, I'm using the { match } for some components, is it fine or it needs to be updated.. maybe by using the useParams, but don't know how to do it as i'm lagging knowledge on it. Also, i want to know how to navigate inside the page.. is it done by using Navlink..? I would be thankful for upgrade to any of the codes below. A CodeSandbox would really help.
Link to -> Sandbox
My Code as below:
       //DATA STRUCTURE
          const Data = [
                {
                 name: "LIGHT FITTINGS",
                 id: "1",

                  resources: [
                               {
                                id: "1a",
                                title: "Bulb",
                                specification: "9W",
                                price: 29.9584,
                                countInStock: 19
                                 },
                                 {
                               id: "2a",
                       title: "Tube light",
                       specification: "9W",
                   price: 39.56,
                   countInStock: 24
                    }
                ]
        },
    {
         name: "SWITCH & SOCKETS",
         id: "2",
             resources: [
                          {
                           id: "1b",
                   title: "Switch",
                   specification: "6A",
                   price: 16,
                   countInStock: 15
                },
              {
            id: "2b",
            title: "Socket",
                specification: "16A",
                price: 39.56,
                countInStock: 24
                }
                  ]
    }
       ];
        export default Data;

   //App.jsx

        import React from "react";
        import { BrowserRouter, Route, Switch } from "react-router-dom";
        import HomeScreen from "../screens/HomeScreen";
        import Products from "../screens/Products";

        function App() {
         return (
            <BrowserRouter>

                  <Route path={"/product/:productId"} component={ProductId}/>
                  <Route path="/products" component={Products} />
                  <Route exact path="/" component={HomeScreen} />

            </BrowserRouter>
            );
            }

        export default App;

   //Product
      import React from "react";
      import Data from "../Data";
      import { Link } from "react-router-dom";

      export default function Products() {
        return (

First page

                    {Data.map(({ name, id }) => (

                       <Link to={`/product/${id}`}>{name}</Link>

                    ))}

                 );
             }

   //Product ID page
    import React from "react";
    import Data from "../Data";
    import { Link, Route, useRouteMatch, Switch } from "react-router-dom";
    import Resource from "./Resource";

    export default function ProductId({ match }) {
        let { path, url } = useRouteMatch();

     const productItem = Data.find(({ id }) => id === match.params.productId);
        return (

ProductId page

{productItem.name}

                    {productItem.resources.map((sub) => (

                        <Link to={`${url}/${sub.id}`}>{sub.title}</Link>

                ))}

                <Route path={`${path}/:subId`} component={Resource} />

         );
         }

    //Resource Page

        import React from "react";
        import Data from "../Data";
        //import { useParams, useRouteMatch } from "react-router-dom";

            export default function Resource({ match }) {
             //let match = useRouteMatch();
            //let { subId } = useParams();

        const productItem = Data.find(({ id }) => id === match.params.productId)
                    .resources.find(({ id }) => id === match.params.subId);

        return (

Resource Page

{productItem.title}

{productItem.price}

                         More Info.

            );
            }

Comment: You need to put them in different routes. And need to use the `exact` property on the routes so only one shows at a time
Comment: hmm.. i tried to put them in different routes... but i could not do it right. .
Answer: Solution

Add exact in the Route for productId so that all sub routes can be handled separately.
 <Route exact path={"/product/:productId"} component={ProductId}/>

Create a new Route pointing to subId.
 <Route path="/product/:productId/:subId" component={Resource} />

This should solve your issue.
Below is the modified codesandbox with working solution.

https://codesandbox.io/s/routing-test-2-forked-k8p64?file=/src/components/App.jsx
Comment: Thank you Sir.. it really did solve my problem. I have one more doubt.. how to navigate inside the page..? say i have a collection of title on the top and when i click it should take to its content which is inside the same page. Is it done using react router.. ?
Comment: You really got my question correct Sir.. I didn't know how to make a separate page so i thougth if i replace the name with /product/ it will show in separate page. I have now added exact path to both /products & /products/:productId and now it is working correctly. Thank you very much Sir. You took the time to answer it.. Thank you..!!
Comment: Glad I was able to help. Yes using react router you can achieve this and you have already used it in your code.

This will take you to the Light Fittings Section.

Also here is one suggestion for you, To list all the products you have used the route as /products and for an individual product, you have used /product/:productId. This should have been /products/:productId Notice the products in /products/: productId. This is not necessary but it is considered a better approach.

Comment if I misunderstood your question.


Oriented Bounding Box algorithm, Need some understanding/clarification of a few lines of existing (working) code

Question: I am reviewing some MATLAB code that is publicly available at the following location:
https://github.com/mattools/matGeom/blob/master/matGeom/geom2d/orientedBox.m
This is an implementation of the rotating calipers algorithm on the convex hull of a set of points in order to compute an oriented bounding box. My review was to understand intuitively how the algorithm works however I seek clarification on certain lines within the file which I am confused on.
On line 44: hull = bsxfun(@minus, hull, center);. This appears to translate all the points within the convex hull set so the calculated centroid is at (0,0). Is there any particular reason why this is performed? My only guess would be that it allows straightforward rotational transforms later on in the code, as rotating about the real origin would cause significant problems.
On line 71 and 74: indA2 = mod(indA, nV) + 1; , indB2 = mod(indB, nV) + 1;. Is this a trick in order to prevent the access index going out of bounds? My guess is to prevent out of bounds access, it will roll the index over upon reaching the end.
On line 125: y2  = - x * sit + y * cot;. This is the correct transformation as the code behaves properly, but I am not sure why this is actually used and different from the other rotational transforms done later and also prior (with the calls to rotateVector). My best guess is that I am simply not visualizing what rotation needs to be done in my head correctly.
Side note: The external function calls vectorAngle, rotateVector, createLine, and distancePointLine can all be found under the same repository, in files named after the function name (as per MATLAB standard). They are relatively uninteresting and do what you would expect aside from the fact that there is normalization of vector angles going on.
Comment: Have you tried asking the author? It is very hard for people to answer questions about individual lines of code from a big function with no context.
Answer: I did not really look at the code, this is an explanation of how the rotating calipers work.
A fundamental property is that the tightest bounding box is such that one of its sides overlaps an edge of the hull. So what you do is essentially

try every edge in turn;
for a given edge, seen as being horizontal, south, find the farthest vertices north, west and east;
evaluate the area or the perimeter of the rectangle that they define;
remember the best area.

It is important to note that when you switch from an edge to the next, the N/W/E vertices can only move forward, and are readily found by finding the next decrease of the relevant coordinate. This is how the total processing time is linear in the number of edges (the search for the initial N/E/W vertices takes 3(N-3) comparisons, then the updates take 3(N-1)+Nn+Nw+Ne comparisons, where Nn, Nw, Ne are the number of moves from a vertex to the next; obviously Nn+Nw+Ne = 3N in total).
The modulos are there to implement the cyclic indexing of the edges and vertices.
Answer: I'm the author of the above piece of code, so I can give some explanations about it:
First of all, the algorithm is indeed a rotating caliper algorithm. In the current implementation, only the width of the algorithm is tested (I did not check the west and est vertice). Actually, it seems the two results correspond most of the time.
Line 44 -> the goal of translating to origin was to improve numerical accuracy. When a polygon is located far away from the origin, coordinates may be large, and close together. Many computation involve products of coordinates. By translating the polygon around the origin, the coordinates are smaller, and the precision of the resulting products are expected to be improved. Well, to be honest, I did not evidenced this effect directly, this is more a careful way of coding than a fix…
Line 71-74! Yes. The idea is to find the index of the next vertex along the polygon. If the current vertex is the last vertex of the polygon, then the next vertex index should be 1. The use of modulo rescale between 0 and N-1. The two lines ensure correct iteration.
Line 125: There are several transformations involved. Using the rotateVector() function, one simply computes the minimal with for a given edge. On line 125, one rotate the points (of the convex hull) to align with the "best" direction (the one that minimizes the width). The last change of coordinates (lines 132->140) is due to the fact that the center of the oriented box is different from the centroid of the polygon. Then we add a shift, which is corrected by the rotation.


Spacing Issue Between Items in Horizontal Scrollable CollectionView

Question: I'm building a collection view using UICollectionViewCompositionalLayout and want to scroll through its items horizontally. I'm having an issue where there is a large gap between some of the items when scrolling. In the image below notice the gap between UI/UX and the next item. How can I reduce this space?

Here is UICollectionViewCompositionalLayout used by the collection view.
static func createLayout() -> UICollectionViewCompositionalLayout {
    return UICollectionViewCompositionalLayout { (sectionNum, env)
        -> NSCollectionLayoutSection? in

        let layoutSize = NSCollectionLayoutSize(
            widthDimension: .estimated(100),
            heightDimension: .absolute(40)
        )

        let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: layoutSize.heightDimension), subitems: [.init(layoutSize: layoutSize)])
        group.interItemSpacing = .fixed(10)

        let section = NSCollectionLayoutSection(group: group)
        section.orthogonalScrollingBehavior = .continuous
        section.contentInsets = .init(top: 0, leading: 12, bottom: 0, trailing: 12)

        return section
    }
}

Here is the cell the collection view uses.
class CellOne: UICollectionViewCell {
    private lazy var label: UILabel = {
       let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textAlignment = .center
        label.font = .systemFont(ofSize: 25)
        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        layer.cornerRadius = 8
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func configure(text: String) {
        self.backgroundColor = .systemRed
        label.text = text
        self.addSubview(label)

        let padding: CGFloat = 10

        NSLayoutConstraint.activate([
            label.topAnchor.constraint(equalTo: self.topAnchor),
            label.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            label.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: padding),
            label.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -padding),
        ])
    }
}

Answer: Try using:
let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: layoutSize.widthDimension, heightDimension: layoutSize.heightDimension), subitems: [.init(layoutSize: layoutSize)])

So we remove:  .fractionalWidth(1) and replace with layoutSize.widthDimension
The goal is to make the group and item the same size.
Comment: But adding `section.interGroupSpacing = 10` fixes that issue.
Comment: Yes, with my solution there is a group for each item. That is generally the standard approach. I have used and seen this in multiple diffrent apps. When you have simple layouts like the one in this question, you do not need any extra layout capabilities the group provides. The section partitions its space amongst the groups.
Comment: So you only have to use groups if you want to build something more complicated like the app store layout. Where in each section you might want to "group" items and display them differently. The photos app is another example of a more complex layout you would use groups for.
Comment: This makes all the cells stick to each other, there is no spacing between them.
Comment: Why do we have to make the group and item the same size? From my understanding, the group is a container for the items and we need to partition that space. With your solution, I'm guessing each item acts as its own group.
Comment: P.S please mark the answer as accepted if that resolved your question


How to simulate HTML5 Drag and Drop events in javascript?

Question: As title, I'm trying to simulate an HTML5 drag and drop event in javascript.
I've looked into jquery.ui.simulate and also the simulate function here. Both seem to be able to be used to simluate drag and drop by simulating mousedown, mousemove, and mouseup which works with jQuery UI objects.
But the drag/drop events in pages like drag and drop demo site do not seem to be simulatable using the same methods. Triggering a mousedown doesn't seem to fire the dragstart HTML5 event.
Is there a way to either get dragstart events to be fired based on a simulating mousedown/mousemove/etc, or is there a way to simulate the dragstart (and then drop) events directly?
I've tried modifying the simulation function found on SO to add the HTML5 dragstart event so I could try something like the following on the demo page
 simulate( document.querySelector('#three'), 'dragstart')

but I get an error because I'm not sure how to create the dataTransfer object on the simulated dragstart event correctly.
Basically, I'll accept any answer that would let me drag element 'three' to the 'bin' element in the demo drag and drop page either using jquery.ui.simluate (or another library) or by using a modified version of the simulate function I found on SO.
Comment: Did you figure out how to do it?
Answer: Your best bet is to recreate a fake event object.
In my unit tests for a drag-and-drop file upload library (Droplit, shameless plug), I have been doing this with jQuery's Event method. In my source code I set my drop event listener with element.ondrop() like so:
element.ondrop = function(e) {
  e.preventDefault();
  readFiles(e.dataTransfer.files);
};

And then I can test this out by building a fake event object and passing it into the ondrop method.
element.ondrop($.Event('drop', {dataTransfer: { files: [] }}));

Answer: You can try this one. It uses native HTML5 events, no jQuery
https://github.com/Photonios/JS-DragAndDrop-Simulator


How do I re-enable the windows key while playing a game?

Question: I've only played a handful of games but, when I pause a game, I usually get control of my mouse to click on something outside of the game in Windows.
If I cannot, I press the windows key and that does the trick.
Now I am playing Doom campaign mode and I cannot figure out a way to click outside the game window and the windows key doesn't work.
I cannot find anything in the settings either.
How can re-enable the windows key in this scenario?
Answer: You're likely looking for the Alt+Tab key combination.
Some games run in full screen mode which disables the windows key. Alt+Tab however will get you out of the active game and back to your desktop. It may minimize the game depending on the settings.
You may also be looking to change your game options to run in "Full Screen Windowed Mode". That will make the game run like it is in a window (and leave the Windows key active) while taking up the entire screen.
Comment: I tried windowed mode too, didn't work. But Alt-Tab worked! Thanks
Comment: Glad to be of help.


jdbc transaction management : when releasing resources and distributed transactions

Question: hello
i'm a beginner java developer and this is one question in a list i'm posting since i've started porting a very old web service . I'm trying to improve the access to db and i'm finding a lot of code i believe migth be dangerous, but being not so experienced with java i cannot be sure .
Actually i've a class which manages the db connection and holds static references to a connection and a statement objects  : it exposes an "openDb" method which initializes the sql connection class member variable.
Problem number 1 : the class member variables are static, what is going to happen if the openDb is called multiple time and the first (for example) instance of the class is still executing a query?
the above class expose a method name "closeDb" which releases all resources (connection and statement both static members! ) and a "closeStatement" method which release only the statement member, and is used externally.
Problem number 2 : stements and resultset must be closed after a transaction committ/rollback or can be closed immediatly?
Still the same class handles the commit/rollback exposing some methods (to set autocommit to false, to commit or rollback ) . An instance of this class is passed to other classes instance (for example the usual employee department classes )  which execute their own queries on the db and finally the commit/rollback is called by the connection manager class . Is this "architecture" correct or do you see any danger in it ?
thank you in advance
Answer: This is a very bad design and the observations you make concerning the static variables are correct. If one thread calls openDb and another thread does the same, things will go wrong. Maybe this happens not all the time which makes this hard to debug.
Concerning problem nr. 2: you should close things once you're done with them. This way you don't keep resources occupied unnecesary. So when you have read all (necessary) data from a result set, close it. It's also not a good idea to have statements and result sets escape the transaction boundary. So instead of:
begin transaction
  open result set
commit transaction
read from result set

you should have:
begin transaction
  open result set
  read from result set
commit transaction

To make the picture complete, you should always have the following pattern when using transactions:
begin transaction
  open connection
    read/modify data
  close connection
commit transaction

The open connection/close connection combination may occur multiple times within one transaction.
EDIT: To complete the picture even more: in the usual scenario, your application has several layers (e.g. UI, business, data). Transactions are usually started and committed inside the business layer. From the business layer you call one or more data layer methods that become a part of the transaction:
// Inside business layer:
public void businessMethod(...) {
    try {
        // Begin transaction.
        dataMethod1(...);
        dataMethod2(...);
        ...
        // Commit transaction.
    }
    catch (...) {
    }
}

// Inside data layer.
public void dataMethod1(...) {
    // Open connection.
    try {
        // Get data from database.
        // Manipulate data.
    }
    finally {
        // Close connection.
    }
}

Some additional notes:

The transaction commit is the final statement inside the try/catch (if you want to return data from your method, it can be followed by a return statement). This ensures that the transaction only commits when everything is ok (i.e. no exception thrown).
The connection close is inside the finally part of the try statement. This ensures that it is always closed, no matter what happens inside your data method.
Comment: The second connection will not cause an exception. It will only run inside the same transaction. You shouldn't worry about reusing the same connection but simply open a new connection when you need one. JDBC uses a connection pool so creating a new connection has hardly any performance impact.
Comment: thank you very much for your fast and clear answer, one more thing : you say open/close connection may happen multiple times, but i suppose it's always the same connection. What about opening different connection inside the same transaction ? will the second conection causes an exception or will the transaction affect only the connection it's associated to ?
Comment: the final two questions : when you say "will run inside the same transaction" do you mean the 2nd connection is part of the 1st connection transaction or the 2nd connection will work indipendently from 1st ? And what's the better strategy for jdbc connections provided by a datasource : open and close connection continuosly or try to use the less number of them (the first option i suppose : not to keep resources occupied )
Comment: This depends on your application design and what makes more sense. If you're inside a single method and you need to go to the database multiple times inside this method, I would use one connection. If your transaction spans multiple method calls, you should open a connection inside each method. I'll add some more info to my answer to illustrate this scenario.
Comment: sorry to bother you so much i meant the following case :  conn1.setAutocommit(false); stmt1 = conn1.createstatement(); ... accessing db one or more time .. localhelperMethod1(); localhelpermethod2(); ... conn1.commit();    if the class local helper methods access db only to retrieve data , their inner connections will be enlisted into conn1 transaction or will be indipendent ? and should i pass them conn1 or can i get their own connection from datasource. thank again for your answers
Comment: Hm, not absolutely sure. I thought you were using the Java Transaction API. I think both helper methods will enlist in the same transactions..


ThenInclude for Explicit Loading in Entity Framework core?

Question: I know I can go one step deeper to load related data using ThenInclude in Eager Loading like below example
//Eager Loading
var publisher = await _context.Publishers
                              .Include(pub => pub.Books)
                                  .ThenInclude(book => book.Sales)
                              .Include(pub => pub.Users)
                              .Where(pub => pub.PubId == id)
                              .FirstOrDefaultAsync();

How can I write the same query in Explicit Loading? How do I load data for Sales without looping through books in below case?
//Explicit Loading
var publisher = await _context.Publishers
                              .SingleAsync(pub => pub.PubId == id);

_context.Entry(publisher)
        .Collection(pub => pub.Books)
        .Load();

_context.Entry(publisher)
        .Collection(pub => pub.Users)
        .Load();

Comment: Loop through each of the books and call Load on each of their Sales collections?
Comment: Ehm, alright.  Why are you averse to writing a loop?
Comment: @RobertHarvey, Thanks for your comment. Is there any way I can do it without looping through "Books". My questions does miss the whole purpose of having explicit loading though.
Answer: Query() method is your friend.
It's partially explained in the Querying related entities subsection of Explicit loading documentation:

You can also get a LINQ query that represents the contents of a navigation property.
This allows you to do things such as running an aggregate operator over the related entities without loading them into memory.
Example...
You can also filter which related entities are loaded into memory.
Example...

What they forgot to mention is that you can use it also for Include / ThenInclude related data of the explicitly loading data.
e.g.
_context.Entry(publisher)
    .Collection(pub => pub.Books)
    .Query() // <--
    .Include(book => book.Sales) // <--
    .Load();


Slow draining shower

Question: Advice please to clear shower drain. I have used bicarbonate soda and vinegar which didn't help. Then I bought a snake auger but when I take chrome cover off shower drain, all I cannot see any sign of the hole leading to pipe work and I've tried feeling for it with flexible wire. If I look under the shower I can see where drain pipe goes off the trap but no entry hole when I try from shower tray.  I wondered if there was a hair trap which should lift out but plastic fitting seems to be secured into shower tray. I've tried turning it but no movement at all. I'd be grateful for any tips. I'd post photo but not sure how to add them.
Comment: Can you provide a picture of the drain so we can see what you see?
Comment: Welcome to [diy.se]. To post your picture, [edit] your post, then simply drag the picture into the text edit box. The site will automatically upload & host the image for you. Alternatively, you can click the "sun & mountain" icon above the text entry box and enter the picture there. If it's fighting back, upload the picture to a site like imgur.com, then paste the share link into the comments, someone will embed it for you.
Comment: Baking or better washing soda used to clean kitchen sink from fat. Shower and washroom sink acid should be used. Just vinegar a.k.a. diluted acetic acid. Stronger acid better but more dangerous.
Comment: This video shows that the drain line can have multiple bents in it making rodding difficult. https://www.bing.com/videos/search?q=how+shower+drain+connects&&view=detail∣=2E0D107D6B908F802F732E0D107D6B908F802F73&&FORM=VRDGAR&ru=%2Fvideos%2Fsearch%3Fq%3Dhow%2Bshower%2Bdrain%2Bconnects%26%26FORM%3DVDVVXX
Answer: I've dealt with this recently with two shower/tubs.
I'm going to assume that you mean a combo and just a shower because those (at least in my experience) go straight down.
For me, it was really hard to tell which way the drain went at the bottom, but it went straight back under the tub. Please don't take this to mean that yours necessarily does.
For the first one, I put a snake down and was able to get quite a bit of hair out. The snake ended up getting stuck on the way out and I deformed it some.
With the second, I just put some lye down the drain. This isn't really ideal especially if you have a septic field, but is fast and easy.
Comment: Top photo is what I see under shower tray. Bottom photo is part that I wonder if it can be removed and if so how?

Slow draining shower


Why is my indoor HVAC unit dripping water all day long?

Question: My HVAC unit is constantly dripping water throughout the day. The dripping is coming from the PVC pipe that runs from the unit to a floor drain.
Just over a week ago, I went to change my 3-month filter and it was soaked. Water seemed to also have leaked out of the unit and pooled up on that metal duct area just to the right of the unit. A day after I put the new filter in, I checked it and it had a little bit of water on it, but now the filter is dry. However, there is still that constant dripping sound.
They want to charge $90 for someone to come out, so I am hoping there can be a DIY solution.
Comment: Those red caps aren't exactly water tight. If you push down on that assembly, and it binds against the black insulation and becomes lower than where it goes into that open tee... it'll leak.
Answer: When the air conditioning is running, it both cools and dehumidifies the air in the home, so water condensing out of the air is normal and expected. That should be dripping into the drain pretty much all the time the A/C is on.
If the drain pan and pipe are not clear, water can back up rather than going down the drain. You may need to clean those.
In heating season, a high-efficiency furnace may also drip, but that will be water condensed from the exhaust gasses of the burnt fuel.
Comment: Probably that was enough, if the filter is no longer getting wet.
Comment: When I noticed the wet filter and water pooling up, I did clean that pipe with a brush tool they provided. There was a lot of lint and debris. The drain pan doesn't appear to be easily accessible without a tool to remove hex screws. If the filter is dry and there is no water pooling up, is it safe to say I cleaned it thoroughly enough with the brush?
Comment: This is related to one of the neatest concepts around cooling: the difference between latent heat and sensible heat. Oversized air conditioners do a bad job reducing latent heat and result in things feeling clammy. Undersized air conditioners will reduce the latent heat and do a great job dehumidifying but will result in a higher temperature because they don't capture all the sensible heat. Right-sized units will hit both targets.
Comment: @flemming It can also be the pipe going down into the floor clogging up somehow. They don't always go to the drain, and sometimes just poke outside where stuff like mud or bugs can get in there. Try pouring a bit of water down the T above the drain to test it.
Comment: I once had a similar problem and removed the panel on the ductwork.  Inside I found a dead mouse plugging the drain hole.
Comment: (Note that the condensate liquid from the exhaust of a condensing boiler is often corrosive, so needs much more care than that from dehumidifiers/AC.)
Comment: @le3th4x0rbot I took your advice and stuck that cleaning brush all the way down into the vertical pipe going into the drain and then flushed it with water. All clear. I then fished some twine through the horizontal pipe connected to it using a magnet, tied a wad of paper towel to the other end, and pulled it through. Only minimal debris. It is very humid here right now, so maybe that has something to do with the sudden, constant dripping. It's quite annoying, but I can learn to deal with it.


Why is it saying not defined?

Question: first off im very new to programing Python 3.4.3, im trying to call 5 entrys and put them into and array and display that, but im stuck at GPA1 not defined, but it is defined in for the entry app
import sys
from tkinter import *

def save_data():

    fileD.write("GPA1:\n")
    fileD.write("%s\n" % GPA1.get())
    fileD.write("GPA2:\n")
    fileD.write("%s\n" % GPA2.get())
    fileD.write("GPA3:\n")
    fileD.write("%s\n" % GPA3.get("1.0", END))

    app = Tk()
    app.title('Student Grade Report')

    gpa1=str(GPA1.get())
    gp1=float(gpa1)
    gpa2=str(GPA2.get())
    gp2=float(gpa2)
    gpa3=str(GPA3.get())
    gp3=float(gpa3)
    gpa4=str(GPA4.get())
    gp4=float(gpa4)
    gpa5=str(GPA5.get())
    gp5=float(gpa5)
    gpas=gp1+gp2+gp3+gp4+gp5
    avg=gpas/5
    def DisplayMsg():
        DL=str("Dean's list")
        AP=str("Academic Probation")
        note=("No Message")
        if (avg>3.5):
        note=DL
    else:
        if (avg<2.0):
            note=AP
    return str(note)

    classi = StringVar()
    classi.set(None)

    Label(app, text = "Classification:").pack()
    Classification = StringVar()
    Classification.set(None)
    Radiobutton(app, variable = classi, text = "freshman", value = "freshman").pack()
    Radiobutton(app, variable = classi, text = "sophmore", value = "sophmore").pack()
    Radiobutton(app, variable = classi, text = "junior", value = "junior").pack()
    Radiobutton(app, variable = classi, text = "senior", value = "senior").pack()

    Label(app, text = "GPA1:").pack()
    GPA1= StringVar()
    GPA1.set(None)
    GPA1= Entry(app,textvariable=Gpa1).pack()
    Label(app, text = "GPA2:").pack()
    GPA2= StringVar()
    GPA2.set(None)
    GPA2 = Entry(app)
    Label(app, text = "GPA3:").pack()
    GPA3= StringVar()
    GPA3.set(None)
    GPA3= Entry(app)
    Label(app, text = "GPA4:").pack()
    GPA4= StringVar()
    GPA4.set(None)
    GPA4= Entry(app)
    Label(app, text = "GPA5:").pack()
    GPA5= StringVar()
    GPA5.set(None)
    GPA5= Entry(app)

    Button(app, text= "Message", command = DisplayMsg).pack()

    Button(app, text = "Save", command = save_data).pack()

    app.mainloop()

Comment: Is your indentation messed up? All the code after `return str(note)` should not be indented, because then it's part of the function.
Comment: Please paste the actual exception and traceback, rather than just a vague description of it.
Answer: The program published above does have some problems with indentation, but I suspect that this happened when inserting into the editor.
Also, I suspect your error says Gpa1 undefined, not GPA1. This is because you assign a text variable to the Entry which is not initialized yet (i.e. it does not exist).
The way you pack() the widgets, make them appear vertically. If you want them in a spreadsheet like table, you have to use a packer such as .grid(), and specify the column and row where you want the widget to appear.
Here's the code, slightly cleaned up (Note that I had to use Tkinter to find the module - not tkinter):
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from Tkinter import *

def save_data():

    fileD.write("GPA1:\n")
    fileD.write("%s\n" % GPA1.get())
    fileD.write("GPA2:\n")
    fileD.write("%s\n" % GPA2.get())
    fileD.write("GPA3:\n")
    fileD.write("%s\n" % GPA3.get("1.0", END))

    app = Tk()
    app.title('Student Grade Report')

    gpa1=str(GPA1.get())
    gp1=float(gpa1)
    gpa2=str(GPA2.get())
    gp2=float(gpa2)
    gpa3=str(GPA3.get())
    gp3=float(gpa3)
    gpa4=str(GPA4.get())
    gp4=float(gpa4)
    gpa5=str(GPA5.get())
    gp5=float(gpa5)
    gpas=gp1+gp2+gp3+gp4+gp5
    avg=gpas/5

def DisplayMsg():
    DL=str("Dean's list")
    AP=str("Academic Probation")
    note=("No Message")

    if (avg>3.5):
        note=DL
    elif (avg<2.0):
            note=AP

    return str(note)

def main():
    app = Tk()
    app.title('Student Grade Report')

    classi = StringVar()
    classi.set(None)

    Label(app, text = "Classification:").pack()
    Classification = StringVar()
    Classification.set(None)
    Radiobutton(app, variable = classi, text = "freshman", value = "freshman").pack()
    Radiobutton(app, variable = classi, text = "sophmore", value = "sophmore").pack()
    Radiobutton(app, variable = classi, text = "junior", value = "junior").pack()
    Radiobutton(app, variable = classi, text = "senior", value = "senior").pack()

    Gpa1 = None

    Label(app, text = "GPA1:").pack()
    GPA1= StringVar()
    GPA1.set(None)
    GPA1= Entry(app,textvariable = Gpa1).pack()

    Label(app, text = "GPA2:").pack()
    GPA2= StringVar()
    GPA2.set(None)
    GPA2 = Entry(app)
    Label(app, text = "GPA3:").pack()

    GPA3= StringVar()
    GPA3.set(None)
    GPA3= Entry(app)
    Label(app, text = "GPA4:").pack()
    GPA4= StringVar()
    GPA4.set(None)
    GPA4= Entry(app)
    Label(app, text = "GPA5:").pack()
    GPA5= StringVar()
    GPA5.set(None)
    GPA5= Entry(app)

    Button(app, text= "Message", command = DisplayMsg).pack()

    Button(app, text = "Save", command = save_data).pack()

    app.mainloop()

main()

NOTE: Sorry! I added a NOTE to the original post, instead of my answer. Here's the correct note: You are not done yet! There are still issues to be resolved. Eg. The fileD.write won't work if you don't open the file first.
Comment: yes there are other things that i have to do like save all the data to a specific .txt document but i have not added that yet
Comment: Traceback (most recent call last):
  File "C:/Users/jace/Documents/Test 4.py", line 18, in
    gpa1=str(GPA1.get())
NameError: name 'GPA1' is not defined                                                                               thats the error i am getting, do i need to add all these to a function and then call them once the entry has been input, @jcoppens
Comment: Try to load the version of the program I uploaded. If you made errors with the indentation, then that could cause the variable GPA1 (and GPA2...) to be invisible to the functions.  The lines from `classi = StringVar()` on should be either at the left margin (as Barmar noted), or in a function (like I did). Else they are considered part of the `save_data` function and that would cause the 'undefined' error.
Answer: You need to fix all the problems described in jcoppens' very thorough answer, but the actual problem you're asking about is another one, that you also need to fix. (I'm assuming that your actual indentation and structure looks like what he's guessed in his answer. If this doesn't apply to your actual code… well, it applies to the code in his answer, which your code will hopefully be a lot like once you fix all the other problems.)

Inside save_data, you do this:
fileD.write("%s\n" % GPA1.get())

But there's no global variable named GPA1, and no local variable inside that function named GPA1.
There is a local variable inside main with that name, but that doesn't help; the whole point of local variables is that they're local—the only live inside one function.
You could fix this by making GPA1 global, by just adding global GPA1 to the top of your main function. This is the quickest solution, but usually not the best.
A better solution is to create a class, and make GPA1 an attribute of that class. Whichever Tkinter docs or tutorial you're using will probably have lots of good examples of this.
You could also change save_data to take GPA1 as a parameter, and then use functools.partial(save_data, GPA1) instead of just save_data, as a callback.
Or you could put all of these functions inside another function and make GPA1 a nonlocal variable instead of a global one. (I wouldn't recommend this, just including it for completeness…)
Of course whatever you do, you need to do the same for GPA2 or you'll just get the same error again two lines later.

Needless to say, there's no guarantee this is the last bug in your program.

Why is it saying not defined?


Pokemon Go Routes Not Working

Question: I have one account that the routes do not appear on. But when I go into another account the routes are there. When I click on the routes map it says "There are no routes nearby", even when I am standing right on one. There could be two things I think it could be.  The account could be under a birthday of a 17 year old, or that it was banned for a week once. But I have no clue to what else it could be.
Answer: Per Niantic Help, this could be one of two things:

Make sure the account is at least level 5.

In order to be able to follow a Route, you must first reach Level 5

For child accounts, make sure the account has the appropriate settings enabled in either Niantic Kids or Pokemon Trainer Club, whichever is applicable

Additionally, if you login with a child account (via Niantic Kids or Pokémon Trainer Club), check the Friends and related features settings in the Parent Portal.

Pokemon Go Routes Not Working


How to "dock" empathy to side of desktop (Digsby style)

Question: I come from a windows background, and one of the coolest apps I used was Digsby.
It was a multi-protocol IM client similar in function to empathy.
Now I like empathy, especially when used with gnome3.
One feature digsby had was the ability to dock it to one side of your desktop, when your mouse collided with that side the contact list would show.
I am looking for the ability to do something similar, or, event better would be the ability to set it to show if I bounce my mouse to the top right corner.
Is there anything that would allow me to do this?
Comment: I'm sure that is not possible yet, someone will have to create a gnome extension for that, or you can submit a bug asking for a feature like that in empathy.
Comment: I want that feature for Pidgin.
Answer: (Terribly sorry that this is two weeks late, but I haven't had the internet besides at work, and there's a firewall there. Here goes...)
First download wmctrl by entering this into your terminal sudo apt-get install wmctrl
Next, you'll need compiz sudo apt-get install compizconfig-settings-manager
Then, within compiz, in the "Commands" section add wmctrl -R "Contact List" Then, from the Edge Bindings tab, select an edge to associate with that command. (if you don't want it to appear instantly, set a time delay in the General section of compiz)
Hope that works for what you need. And once again, sorry the answer came so late.
Comment: If it's no inconvenience, you should provide the step by step instructions anyways.
Comment: please, that would be awesome


php - file_get_contents() or similar function

Question: I'm using file_get_contents() to retrieve a list of counties that I have stored in a .txt file. Each county is on its own line.
Is there a way to add quotations around each entry and then a comma following it within the function? One restriction I have is that it would have to populate within the function, and cannot be two separate commands.
Can this be done?
Or maybe I need to look into another function for this?
Comment: Why can you not use two functions?
Comment: `One restriction I have is that it would have to populate within the function` - why? What is the end result you want here - are you writing to a CSV or something?
Comment: What do you mean two separate commands?
Comment: @Jleagle @DaveRandom; I'm editing an application of ours, and we're only allowed to edit a specific file to add an additional field to a form. This file is grabbed by another file which translates the lines and does something with it to populate the fields (which we do not have authorization to access that file). Because of this, adding any other additional commands breaks the operation.
Comment: Any reason why this received a downvote?
Comment: Maybe because of the strange requirements of limiting it to one function. (I didn't downvote).
Answer: $countries = file('countries.txt'); // get country list into an array

$fixed_countries = array_map(function($v) { return '"' . trim($v) . '",'; }, $countries);

Comment: I went ahead and used a batch script to repopulate my list with the appropriate quotations and commas, reinported the file to the server, then used file() to populate the array. Worked like a charm. Thanks
Answer: You can do it pretty easily, and it's even better if you use file instead of file_get_contents:
$callback = create_function('$c', 'return "\"".trim($c)."\"";');
$countries = array_map($callback, file('countries.txt'));
return implode(', ', $countries);

I have written $callback with a syntax that is valid for PHP < 5.3; it's also possible to write it as an anonymous function:
$callback = function($c) { return '"'.trim($c).'"'; };

See it in action.
Comment: Downvoter: please help me to improve this answer by leaving a comment.
Answer: If you read something line-by-line, file is more appropriate than file_get_contents:
echo implode(',',
             array_map(function($county) {return '"' . trim($county) . '"';}),
                       file('counties.txt'));

Answer: Sure.
$countries = explode("\n",'"'.str_replace("\n","\",\n\"",file("countries.txt")));

That should convert the file like this:
country1
country2
...

into an array like this:
array('"country1",','"country2",',...).

That's what you want, right?
Comment: The result of this would be `array(0 => '"Array')` because you are appending an array to a string.


Highest Twin primes such that the number in between twins is the $\text{lcm}$ of first $N$ numbers

Question: $\text{lcm}(1,2,3,4,5,6,7) = 420$ and this number is placed between two Twin primes: $419,\ 421$.
This happens again for $\text{lcm}(1,2,3...19) = 232792560$ and
$\text{lcm}(1,2,3,4,...,47)=442720643463713815200$ that is  placed between the 2 Twin primes:
$$442720643463713815199 \\
442720643463713815201$$
However it does not happen again up to where I could reach about $\text{lcm}(1,2,3..., 44983).$
Is $N=47$ the largest number such that $\text{lcm}(1,2,3,...,N)$ is placed between two Twin primes?
I find this huge gap between 47 and, at least, 44983, highly counter-intuitive. There could be a good reason for this.
Complete list :
$$\text{lcm}(1,2,3) = 6 \text{  Twin primes: 5 7}$$
$$\text{lcm}(1,2,3,4) = 12 \text{  Twin primes: 11 13}$$
$$\text{lcm}(1,2,3,4,5) = 60 \text{  Twin primes: 59 61}$$
$$\text{lcm}(1,2,3,4,5,6) = 60 \text{  Twin primes: 59 61}$$
$$\text{lcm}(1,2,3,4,5,6,7) = 420 \text{  Twin primes: 419 421}$$
$$\text{lcm}(1,2,3,...,19) = 232792560 \text{  Twin primes: 232792559 232792561}$$
(then 47 already mentioned above)
I also add a very simple code in python, using the sympy library, so everyone can verify this.
<code>    from sympy import *

    lcmi=2
    for i in range(3,100000):
        print "Evaluating lcm of first", i, "numbers"
        ni= lcm(lcmi,i)
        if ni != lcmi:
         if isprime(ni-1) and isprime(ni+1):
            print i,"lcm:", ni,"Twin primes:", ni-1, ni+1
         lcmi=ni
</code>
Comment: https://oeis.org/A057822 only verified the result up to 2000.
Comment: @rtomas you should list all numbers between $N=1, \dots, 47$ such that it works.  E.g. $\text{lcm}(2,3,4) = 12$  and $\pm 1 = 11,13$.
Comment: I do not think that we will be able to rule out infinite many twin-primes of this form.We can however find out a heuristic result based on the probability that $n$ is surrounded by a twin-prime pair (here we have to consider that small prime factors are ruled out). Mabye, someone will do this.
Comment: Thanks a lot @player3236 !
Comment: excellent suggestion @CommutativeAlgebraStudent , I did so.
Comment: I just found this interesting work: https://arxiv.org/pdf/1106.6050.pdf  That demonstrates that the number between 2 Twin primes cannot be expressed as as $36ab\pm 6a\pm 6b$, with $a$ and $b$ natural numbers. Maybe the lcm's for N above 47 are always of that form?
Comment: You are right @Peter.  Some suggestions on how to go about your proposal would be welcome.
Comment: For single primes, such heuristics are easier because we can well estimate the effect if small prime factors can be ruled out. I am not sure whether this is also feasible for a pair of numbers with difference $2$ having no small prime factors.
Comment: I made another post for the heuristics: https://math.stackexchange.com/questions/3956379/correct-reasoning-for-a-finite-number-of-twin-primes-next-to-the-lcm-of-first-n  Also, I have been updating the post with largest N without meeting Twin primes from numerical search from the initially posted N=5000 to the latest one of  N=44983.
Answer: Write $a_n := \operatorname{lcm}(1, 2, \ldots, n)$.
When you're looking at $n=7$ you're considering the pair $420\pm 1$.  The form of these numbers excludes the prime factors 2, 3, 5, and 7, and $\sqrt{420} \approx 20.5$, so the only potential remaining prime factors are 11, 13, 17, and 19.
On the other hand, when you're looking at, say, $n = 9$, you're considering $2520\pm 1$, and $\sqrt{2520} \approx 50.2$.  The form of these numbers still excludes only 2, 3, 5, and 7 as prime factors, but now in addition to 11, 13, 17, and 19 you have to worry about 23, 27, 29, 31, 37, 41, 43, and 47.
Now $a_n = e^{n + o(n)}$ (see Chebyshev's function), so the number of primes less than $\sqrt{a_n}$ grows faster than linear in $n$, while the number of primes less than $n$ (i.e. the number of primes excluded as factors of $a_n \pm 1$) grows slower than linearly.
As a result, going only by this we'd expect exactly the sort of behavior you see here: true for all sufficiently small $n$, and then sporadically true for a few larger numbers if the pieces fall into place.
Of course that doesn't prove anything, but it does tell us that the numerical evidence here isn't pointing towards anything unusual, and therefore likely gives us no help in trying to prove or disprove that there are infinitely many $n$ for which $a_n \pm 1$ are relatively prime.
Comment: right, I made another post with similar arguments: https://math.stackexchange.com/questions/3956379/correct-reasoning-for-a-finite-number-of-twin-primes-next-to-the-lcm-of-first-n  Actually suggesting that there are only finmite $a_n$ such $a_n\pm1$ are twin primes. What do you think?


Filepicker modal only displayed after initial page load in meteor

Question: When I call filepicker.pickAndStore() for the first time in a template everything works fine. Also closing the modal and clicking the button again works fine (modal is displayed again). When I click on a link inside my meteor app to get to another page (of course via html5 pushstate like on every meteor page, no standard a links with a real page refresh) and then go back to the page with the filepicker stuff in it, the button does not do anything anymore. The filepicker modal or anything is NOT displayed. And i also tried call back function as given in the documentation. I'am describing my code below
<code>Template.content.events({
   'click #top_add_file': function (evt) {
    evt.preventDefault();
    console.log("upload file button is clicked")
    Session.set("widgetSet", false);

    if (!Session.get("widgetSet")) {
  var cb = function () {
    filepicker.pickAndStore(
        {
            mimetypes: ['application/pdf', 'application/msword',     'application/mspowerpoint', 'text/plain'],
            container: 'window',
            services: ['COMPUTER'],
            folders: true
        },
        {
            location: 'S3'
        },
        function (InkBlob) {
            console.log("InkBlob="+InkBlob)
            InkBlob.forEach(function (ib) {
                Meteor.call("createContent", ib, Meteor.content_file, function (error, result) {
                    if (error) {
                        FlashMessages.sendError("Error in saving file")
                    } else {
                        FlashMessages.sendSuccess("Successfully Saved File")
                    }

                })
            })
        },
        function (FPError) {

            FlashMessages.sendError("Error in uploading file. Please try again")

        }

     )
  };
  loadPicker(Meteor.fpkey, cb);
}

},
</code>
Comment: Do you get any error in the browser console when you go back to the relevant page?
Answer: The answers to this StackOverflow question may help:
  Integrating Filepicker.IO with Meteor
One of them highlights an atmosphere package for filepicker:
  https://github.com/guido4000/loadpicker
Also, this example shows integrating a 3rd-party modal component into meteor:
  https://github.com/alanning/meteor-modal-example


Is it ok to format bootable usb Pendrive after install finished ubuntu 18.04?

Question: Formating USB(pendrive) after installing done in Dell laptop.
Comment: If you just unplug it and turn on your computer and no error is displayed then you can surely format that. But if any error is displayed then you need to worry. Just unplug pendrive and see what happens.
Comment: in short yes. But sometimes it may happen that your pendrive will show less storage than expected. In that scenario just create filesystem again on pendrive.
Comment: Once i formatted  my bootable pendrive.After that my computer asked me to connect bootable USB and was not operating system on my computer so I am little scared to format it.
Comment: If you booted the usb `toram` you could even umount & format the USB right then
Comment: If you made the stick using Startup Disk Creator, you might have a hard time unmountingd the ISO9660 partition to format. you can use Disks to unmount and then GParted to reformat. mkusb should also work.
Comment: @Karel: I don't think the "Duplicated" post you have chosen relates to this question.
Answer: If you installed Ubuntu 18.04 on your local hard drive from an USB stick, and the installation succeeded, first reboot your computer without the stick connected to check that everything is working fine, and if it is, you can format your USB drive directly from your new ubuntu installation, assuming you won't need to use it for installing Ubuntu again.
Answer: Often during install the grub bootloader gets put on the Installer pendrive rather than the HDD, in which case the pendrive needs to be plugged in to boot.
Try installing using "Something else", when you get to the partitioning stage.
Confirm that the HDD is chosen for bootloader location.


Is there a way to make every item of a JList have different widths?

Question: I'm trying to display Strings in rows and columns. Since they differ in length and represent parts of a continuous text, I would like each component to only take up the size it needs to show the whole String.
So far, I managed to load the individual items into the list, limit the number of rows and make them wrap horizontally. I now wrote a custom ListCellRenderer as I figured this could solve my problem but it doesn't work the way I had hoped. The two Strings that are part of each item are neither centered nor displayed above one another (in fact, they are not readable at all because they seem to be drawn outside the cell) and they all have the same size. What am I doing wrong?
This is what my Renderer looks like:
public class ElementRenderer extends JPanel implements ListCellRenderer<Element> {
    private Element element;

    @Override
    public Component getListCellRendererComponent(JList<? extends Element> list, Element value, int index,
            boolean isSelected, boolean cellHasFocus) {
        element = (Element) value;
        if (element.getTag().equals("N/A"))
            setEnabled(false);
        else
            setEnabled(true);
        if (isSelected)
            setBorder(BorderFactory.createLoweredSoftBevelBorder());
        else
            setBorder(BorderFactory.createRaisedSoftBevelBorder());
        return this;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (!isEnabled())
            setBackground(Color.GRAY);

        String word = element.getWord();
        String tag = element.getTag();

        FontMetrics fm = getFontMetrics(DataManager.getCurrentFont());
        Rectangle bounds = getVisibleRect();

        int y = bounds.y + ((bounds.height - 2*fm.getHeight())/2) + fm.getAscent();
        g.drawString(word, bounds.x + (bounds.width - fm.stringWidth(word))/2, y);
        g.drawString(tag, bounds.x + (bounds.width - fm.stringWidth(tag))/2, y + fm.getHeight());
    }

    @Override
    public Dimension getPreferredSize() {
        FontMetrics fm = getFontMetrics(DataManager.getCurrentFont());
        int wordwidth = fm.stringWidth(element.getWord());
        int tagwidth = fm.stringWidth(element.getTag());
        if (tagwidth > wordwidth)
            wordwidth = tagwidth;
        return new Dimension(17+wordwidth, 3+fm.getHeight()*2);
    }

Answer: Well the simplest solution I could find without messing with the JList's LayoutManager, nor its ListUI, is indeed to create a custom ListCellRenderer, but with the following logic:

The custom ListCellRenderer is a JPanel with a DefaultListCellRenderer in it.
The custom ListCellRenderer, as a JPanel, will fill the entire cell space.
The DefaultListCellRenderer will be centered inside our custom ListCellRenderer. We can achieve this by setting the LayoutManager of the JPanel to GridBagLayout. Since there will be added only a single component in it (ie the DefaultListCellRenderer which is a JLabel), it will be centered.

Follows sample code:
import java.awt.Component;
import java.awt.GridBagLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

public class Main {
    public static class DynamicWidthListCellRenderer extends JPanel implements ListCellRenderer {
        private final DefaultListCellRenderer delegate;

        public DynamicWidthListCellRenderer() {
            super(new GridBagLayout());
            delegate = new DefaultListCellRenderer();
            super.add(delegate);
        }

        @Override
        public Component getListCellRendererComponent(final JList list,
                                                      final Object value,
                                                      final int index,
                                                      final boolean isSelected,
                                                      final boolean cellHasFocus) {
            delegate.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            //super.setBackground(delegate.getBackground()); //Test this out also...
            return this;
        }
    }

    public static void main(final String[] args) {
        final JList<String> list = new JList<>(new String[]{"abc", "abcdefghijklmnop", "abcdefg", "a"});
        list.setCellRenderer(new DynamicWidthListCellRenderer());

        final JFrame frame = new JFrame("List variable width cells");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(list);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

And sample screenshot (with a selected element):


Papa Parse and Leaflet integration for icons

Question: I'm trying to use PapaParse to pull from a Google Sheets CSV which has lat/lon and some options for setting markers with different icons in Leaflet. Everything appears to be working fine. The markers get set correct with the correct color from the CSV. The problem is that the icons aren't loading, even though the console log shows them as parsing correctly.
Here's the spreadsheet: https://docs.google.com/spreadsheets/d/1cGkXzVfq3gE5hRFEj9f2_ffKPjei57R3J99n_t0zy6M/edit?usp=sharing
Here's the full javascript:
 // URL for points CSV download
let pointsURL =
  "https://docs.google.com/spreadsheets/d/e/2PACX-1vSXery2RhtJDVQox_vzESecIMee9nsQZvs7j7IP6SI0huDOV7wSNX_2DEuKdHpR6jXs0Ft1sKukr5pG/pub?output=csv";
window.addEventListener("DOMContentLoaded", init);

// Map function
function init() {
    // Create map
    map = L.map("map").setView([40.749299,  -73.978141], 11);
    L.tileLayer(
      "https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}{r}.png",
      {
        maxZoom: 19,
      }
    ).addTo(map);

    //Parse google sheets
    Papa.parse(pointsURL, {
        download: true,
        header: true,
        complete: addPoints,
      });
    }

    //add points from CSV to the map
    function addPoints(data) {
        data = data.data;

    //create a layer group to add the points to
    let pointGroupLayer = L.layerGroup().addTo(map);
    let markerType = "marker";
    let markerRadius = 100;

    for (let row = 0; row < data.length; row++) {
        let marker;
        marker = L.marker([data[row].lat, data[row].lon]);

    //add custom icons from Google Sheet CSV
    console.log(data[row].color);
    console.log(data[row].icon);

    let icon = L.AwesomeMarkers.icon({
      icon: data[row].icon,
      markerColor: data[row].color,
      prefix: "fa"
    });
    marker.setIcon(icon);
    marker.addTo(pointGroupLayer);
    }
    }

It appears that icon: data[row].icon isn't working. If I do icon: "info-circle", which is also how it is it my CSV, it works just fine. The console.log(data[row].icon) shows "info-circle". Any ideas?
Answer: Remove " from the icon string in the Sheet. "bicycle" to bicycle
Maybe else it has blanks and you need to trim the icon string
Comment: Simplifyed said: in JavaScript you need only the `"` to say that this is a string and not a variable with that name. With parsing from the Sheet the parser already knows that it is a value and not a variable so it don't need `"`.  The value of `data[row].icon` is not printed 1:1 in the script, and javascript self don't need `"` to know that it is a String. This is only for human readability. I hope it is a little bit clearer, it is hard for me to explain :s
Comment: It was that simple. Thanks!

Are you able to explain why that is? I thought the 'data[row].icon' would place what is being parsed exactly as in the spreadsheet, and because if I don't reference the spreadsheet, I need quotations like 'icon: "info-circle"'
Comment: That makes sense. Thanks!


Venting by gas meter

Question: We're looking at installing a natural gas tankless water heater, but the vent option with it (that would be easiest to install through our solid poured walls) would come out about a foot away from the gas meter. The gas company's rule is that the vent can't be within 3' of the meter, so that it doesn't mess with the regulator and such. However, we've seen and heard of the option of coming out there still, but then running the vent up 3' or so with an extension to clear the meter. Is this a working solution or does the vent pipe as well have to be 3' away?
We're not looking to do the gas work ourselves, but I'm still trying to find a plumber who will or has time to. The only one who has looked at it mentioned needing the extension, but said he'd prefer to relocate the vent and told us to figure something out ourselves.
Comment: I'd contact the gas supplier, and see what they say.  Also keep in mind, any 90° elbows likely adds 6' or so to the developed length of the vent pipe. So a 90° + 3' = 9' developed length (check the manufacturer's documentation for exact additional length requirements).
Comment: @Tester101 It appears to allow a span of 41' for the vent for this model. Where I'm looking at would place it at only a vent length of say 5' to the outside, so it definitely gives space to get it far enough from the meter. Based on the manual, it gives clearances and an image; in Canada the 3' is from the centerline of the meter to either side, and at least 15' up in this zone. However the US clearances aren't included for the meter situation. Everyone is closed today so that's why I'm asking here though.
Comment: I guess running vent to the other wall would work as well as an option, as I'd believe it could make it over in 41', but there isn't exactly a clear shot to that wall.
Answer: I called the gas company (I wasn't able to originally when posting the question as it was Saturday) and they said that the 3' is from any side of the meter - so essentially a bubble around it. As long as the vent itself clears this, it'll be fine.
I'd also called the tankless water heater manufacturer located in the US, but they said that this could vary by gas supplier. So although my gas company allows a 3' bubble, others might be more like the Canadian code and require 3' on either side up to 15' above.
Just for reference as well, the gas company was also able to look up the BTU output of my meter from within their system to tell me how much I could load it down with.

Venting by gas meter


Gitlab Wiki same page links

Question: How do I use same page links in the Gitlab wiki? For example:
Contents

 - heading1 ---> this should move the page to heading 1
 - heading2
 - heading3
 - heading4

HEADING 1

Basically I am trying to create a page like Wikipedia where you can navigate a single page using a table of contents.
Answer: This has been added in this pull request.
It generates toc_x anchors, with x incremented for each new header.
If you define a link like:
 [My link to third header](#toc_3)

It will link you to the current page third header (no matter what level that header is).

Gitlab Wiki same page links