How to use replace in android room database sql?

Question:     @Query("update bookmarks set bookmarks_path= replace(bookmarks_path,:oldPath,:newPath) where bookmarks_path like :oldPath || '%'")
    fun updateBookmarksPath(oldPath: String, newPath: String): Completable

I am using the room database and this is my code
I found that the format of this code is not correct when running, android studio prompts me: expression expected, got'replace'
like this

I want to achieve the effect like this
----path------------------path
/root/1/1--------------/stack/1/1
/root/name/1------/stack/name/1
/root/cls/1-----------/stack/cls/1
/root/go/1-----------/stack/go/1
/root/js/1------------/stack/js/1
please
Comment: I don't understand why You want do to string operations in Your sql statement. I wouldn't to that. In fact room doesn't support all SQL statements. Probably `replace` is one of them.
Comment: If I modify it in the code, I need to search for all the data that matches, and modify them, and modify them again in the database, using this method can directly modify them, this SQL can be executed, although the error still exists, I think this may be SQL syntax correction, but does not affect code execution
Comment: as Bob Snyder mentioned, it works with backticks
Answer: REPLACE is both an SQLite keyword and, in the case of your intended use, the name of a string function: replace() .
The Room annotation processor appears to be rejecting your query string because it is treating replace as keyword instead of function name. Maybe a bug?
Some quick experiments indicate that a possible solution is to surround replace in backticks to mark is as a name (see keyword link above).  Please give it a try:
@Query("update bookmarks set bookmarks_path= `replace`(bookmarks_path,:oldPath,:newPath) where bookmarks_path like :oldPath || '%'")
fun updateBookmarksPath(oldPath: String, newPath: String): Completable

Comment: Thanks for your answer,When using this method, the error is: There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (near "(": syntax error), I try to run without modifying anything, it can run successfully, and can To achieve the effect I want, although he prompts an error, it can still be built
Comment: Please edit your question to include the revised query string (with the backticks) and all the error output.  Are you sure the error is for this query?  The syntax I included in my answer is valid.  I've tested it using sqlite3 and don't get an error.
Comment: Also, please note that the characters added around `replace` are backticks (ASCII code 96) **not** single quotes.  I think you entered single quotes.
Comment: Thank you, you are right, I am too careless, the modified sql will run normally, the single quotes I used are wrong, your answer has been adopted.


Do Occident or Oriental homes produce more net income?

Question: In the current game I'm playing, I'm at a cross-roads on whether to build another Occidental colony or an Oriental one, for money production.  I have enough excess supply that building either one would be easier, but I'd like to know which type of colony generates more money after maintenance and supply costs per house?
So if I have a fully surrounded market place, with all the requisite support buildings, which type of population earns more money?
Answer: The Oriental ones don't have as many levels to reach, but their initial income should be higher.
Answer: Occidental towns have a strongly deminishing tax return depending on city size. Up to about 500 people per class (peasant, citizen...) produce maximum tax.
Orientals produce much less tax, but it does not diminish like it does for occidentals. So large oriental towns are likely better than large occidental ones. While small occidental towns are by far the best tax providers. Also note that dates and milk are much more costly to produce than fish and cider.


How to plot contours with selected colors and formatted labels

Question: I'm trying to plot contour using my computed data with limited contour labels and and colors as given in the top panel of this image:

But I ended up with a slightly different plot (see the plot in the bottom of the above image).
I want to modify my plot with the following three specifications

Restrict contour labels in 2 or 3 decimal places
Remove plot labels in the area where the contours are too close to  each other.
Plot with two colors as in the first image

Here is my code:
f=load('fort.15');
ngridx=180;
ngridy=180;
x=f(:,3);
y=f(:,4);
z=f(:,5);
xlin=linspace(min(x),max(x),ngridx);
ylin=linspace(min(y),max(y),ngridy);
[X,Y]=meshgrid(xlin,ylin);
Z=griddata(x,y,z,X,Y,'linear');
[c,h] = contour(X,Y,Z,20);
set(h,'LineWidth',2,'LineColor',rgb('SteelBlue'),'ShowText','on',...
      'LabelSpacing',800 )
axis([0 6 -5 7])

I'm not an expert in Matlab. Please help me get the right plot.
I'm attaching my data file here.
Answer: Well, I got only 2 of 3. Deine the level in which the color has to change (here scl) and you good to go:
scl = 6.5; % switch color level;
[c1,h1] = contour(X,Y,Z,scl:max(Z(:)),'Color','r');
hold on
[c2,h2] = contour(X,Y,Z,min(Z(:)):scl,'Color','b');
clabel(c2,h2);
axis([0 6 -5 7])

The idea here is to builed your plot from two contour objects, using hold on command. the vector scl:max(Z(:)) define the levvels to show in the first contour, and the get the red color and no lables. And a similar logic works for the secound contour.
If you want to lable some red contours, or remove lables from the blue ones, you need to replace h2 in the clabel function with a vector of the levels you want to lable. If you will be mo specific in the comments I'll update my answer.

Changing the formatting of the lables, is probably possible somehow, but it's really not trivial, so I left it by now.
Comment: Thank you friend. It works. But I need more blue contour lines. What should I do for that?


extjs datecolumn shows date one day off

Question: I have an Ext.grid with a datecolumn.  Everything works fine, except that the dates are one day off.
I have found that when I add the data to the grid's store, the value is 2013-03-31.  Later, when I look at the store's data, the value is Sat Mar 30 2013 17:00:00 GMT-0700 (US Mountain Standard Time)
Obviously, this is a Timezone problem, but I have no idea how to fix it.
Here is the code where I add the data to the grid's store
for (var i = 0; i < dateboxes.length; i++)
{
    dateboxGrid.store.add(dateboxes[i]);
    //dateboxes[i].Value contains the date in this form: "2013-03-31"
}
console.log(dateboxGrid.getStore()) //logs "Sat Mar 30 2013 17:00:00 GMT-0700 (US Mountain Standard Time)"

What do I need to do to dateboxes[i].Value before I add it to the store to make sure the intended date shows in the column?
Update
I made the following change.  When I save the date to the database, I first call .toISOString() on the data.  Now, when the data is loaded into the store from the database, it is loaded as GMT +0700, and the date looks right when it's loaded into the field.
However...I'm afraid that means it will show up wrong for someone in a different timezone.
All I want is a Date.  I don't even want to record time.  It makes no sense in my application.
Comment: I don't know much about extjs, but I would try adding a 'Z' after the date, so that it would be in the form "2013-03-31Z".  This should result in the time being saved without any time zone offset.  See [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601#UTC).
Comment: Adding a "Z" to the end of the date didn't work.
Answer: As I worked with this, I found that I either had to overcome one problem or the other.
(1) If I used datecolumn with an editor of datefield, and the field in the store's model was of type: 'date' then the values would be stored in the database as dates (including time).  When I tried to retrieve the dates, then the Timezone thing would kick in and change the date that was loaded.
or
(2) If I didn't use datecolumn and set the store's model to type: 'date' then dates weren't showing up in the cells.  Even though they would get stored as simple strings, they didn't show up correctly in the grid.
Here is what I came to:
I used option (1), but before the store's data was sent to the database, I did this:
    for (var i = 0; i < dateboxes.length; i++) {
        if (dateboxes[i].Value != null) {
            var date = new Date(dateboxes[i].Value);
            dateboxes[i].Value = String(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate());
        }
    }

This basically just changes the Date into a String.  Now the data is stored in the database as a simple string.  When it is displayed in the grid, there is no timezone information to mess it up.  The code `(date.getMonth() +1)' is there, because month is 0 based.
As I look back on the answer, something doesn't make sense.  I must have also changed something else.  Either way...it works now.
I'll leave the question open for someone else to explain better what is going on.
Answer: I don't think this has to do with timestamp. Looking at the source code for encodeDate ... it looks like ExtJS increments the month, but not the day. I'm guessing this was their attempt at a fix.  I got around it by overriding encodeDate in my javascript:
var fFbegin_settle_date = new Date();

Ext.util.JSON.encodeDate = function(fFbegin_settle_date) {
     //didn't work: return fFdateBegin.format('"Y-m-d"');
    pad = function(n) {
        return n < 10 ? "0" + n : n;
    }
    return '"' + fFdateBegin.getFullYear() + "-" +
    pad(fFdateBegin.getMonth()+1) + "-" +
    pad(fFdateBegin.getDate()+1) + '"';
};

extjs datecolumn shows date one day off


possible to have too much soffit intake venting for roof/attic?

Question: Is it possible to have too much soffit intake? Currently my simple gable roof on a ranch home has 8 RVO38 vents but NO soffit intake vents (terrible!). Of course the attic space runs incredibly hot and is not doing me any favors. I need to get the venting improved pronto.
The soffit boards sag and have signs of water damage from previous owner's overflowing gutters, so I wanted to replace them with some t&g cedar and put in a continuous soffit vent. If that didn't help attic venting I would have a ridgeline vent installed. Would it potentially be bad to give myself all that soffit venting or could I try that and see if it is adequate before going to a ridgeline vent?
Comment: sorry for delayed response, was on vacation. I've got approximately 10 RVO38 vents. I researched this more and it seems like unless it is allowing bug or animal ingress, there isn't actually such a thing as too much input down low.
Comment: I have no experience in this area but have a similar situation - only have 6 intakes on a 2500sqf house.  Thus looking to add some more as well.  What are you setup like for exhaust on the roof ( # turbines, etc)?
Answer: You generally want a balanced system with equal intake and exhaust areas, but if you can't balance the system, then there should be more intake area so none of the exhausts (usually near the peak) get back-drawn and act as intakes.
Answer: Intake vents are incredibly important, I believe at least 1 every 8' in all eve soffit areas. The exhaust vents may be passive or powered. The most important thing about the exhaust vents is to install them at the highest portion of the roof. Never allow ridge vents or any exhaust vents to be more that 2' difference in the height of the roof. If you do install with the height difference of more than 2' you'll cause a short cycle between the exhaust vents instead of drawing from the intake vents. All of this I'd determined how the attic is built. Sloped ceilings require a very specific way to vent as well as roofs that are sectioned off where the air doesn't travel throughout the entire home. When in doubt, it's always best to have an expert review the home and advise you for the best results. I've read quite a bit on this site, it's true, no heat or cooling is lost from ventilation, as long as you have enough insulation, vent all you can to keep the home dry and the roof from baking.
Comment: Welcome to [diy.se]! I've edited for a couple of minor formatting issues, but this still remains a wall-o-text and is difficult to parse. Please [edit] to include some formatting to make it easier to read. Also, if you'll read [how to answer](https://diy.stackexchange.com/help/how-to-answer), you'll get some tips on what makes a good answer. In particular, it should actually address the question. Unless it's lost in there, I don't see where you address the question of "_Can I have **too much** soffit intake venting?_".


Do programmers should train in ACM-contests?

Question: A lot of those coders, who are succeed contests like TopCoder SRMs, or Google Codejam, etc., get good jobs and salary. But is it really neccesary? I mean, do all code developers should know different algorithms, structures, or all this contests are just wasting of time?
The problem is those contests take much time - to train, to study, to take part in. I am a student, so I haven't much free time. So I should make a decision: or I do it (in case this gives me knoledges that are useful in future), or I just forget about it and study something else.
Any ideas?
Answer: I think you need to think about what you want from your career 1st and then see what you need to do to get there.  If after doing that, you have proof that succeeding in these contests results in good jobs / salary in an area that interests you then I think you have your answer.
Answer: Knowing and understanding a range of different algorithms, design patterns, languages and hardware specifics gives you a greater flexibility when it comes to job hunting. As such i think these competitions are an excellent way to learn (either as a participant or as an observer) some new skills and increase your hire-ability.
Answer:
I mean, do all code developers should know different algorithms, structures?

Yep, they should (only the good ones:)
Btw, if you want to learn project euler is a great place to start. The good thing is that you can see other people solution so you learn much faster then on ACM. Code Jam also has that option but there is not a lot of problems there.


Setting up CSGO dedicated server with Hamachi

Question: I installed a csgo dedicated and then i added a server.cfg, installed sourcmod and metamod. When i was done i connected to xx.xx.xxx.xx:27015 but i couldn't connect.
I got the error "Disconnected after 30 retries", am i doing something wrong?
What i've tried

I tried setting the server lan to both 0 and 1
I tried setting the server ip and netaddr to 0.0.0.0
I tried connecting via localhost

Have i done something wrong?
Edit
http://pastebin.com/qZPzKVcB - Contains Server.cfg and Start.bat
Answer: You need to find out your external IP address. Google "what is my ip address" and Google will tell you what it is. Give that as the +ip and +net_public_addr parameters, and try connecting on that IP address + port.


Autowiring Spring Beans by Interface

Question: I'm trying to do hexagonal architecture in my Project.
The module structure looks like this:

I don't want domain(core) module to be dependant on other modules. It's logic should be exposed through api, hence I want other modules/clients, like a rest module, to be dependant on the API module only.
I want to use RestaurantServiceImpl (from module core) through an interface RestaurantService (from module api). Spring has trouble autowiring a Bean for an interface RestaurantService. Here  is RestaurantServiceImpl which should register correctly as a spring bean:
@Service
public class RestaurantServiceImpl implements RestaurantService {

    private final RestaurantRepository restaurantRepository;

    @Autowired
    public RestaurantServiceImpl(RestaurantRepository restaurantRepository) {
        this.restaurantRepository = restaurantRepository;
    }

    @Override
    public Optional<Restaurant> getById(RestaurantId restaurantId) {
        return restaurantRepository.findById(restaurantId);
    }
}

restaurant-management-api/pom.xml
<parent>
    <artifactId>restaurant-management</artifactId>
    <groupId>com.jc</groupId>
    <version>1</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>restaurant-management-api</artifactId>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.7</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.4</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

restaurant-management-core/pom.xml
<parent>
    <artifactId>restaurant-management</artifactId>
    <groupId>com.jc</groupId>
    <version>1</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>restaurant-management-core</artifactId>
<dependencies>

    <dependency>
        <groupId>com.jc</groupId>
        <artifactId>restaurant-management-api</artifactId>
        <version>1</version>
   </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.7</version>
    </dependency>

    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>javax.persistence-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.4</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

restaurant-management-rest/pom.xml
<parent>
    <artifactId>restaurant-management</artifactId>
    <groupId>com.jc</groupId>
    <version>1</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>restaurant-management-rest</artifactId>
<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.3.7</version>
    </dependency>
    <dependency>
        <groupId>com.jc</groupId>
        <artifactId>restaurant-management-api</artifactId>
        <version>1</version>
    </dependency>
</dependencies>

restaurant-management/pom.xml
<artifactId>restaurant-management</artifactId>
<packaging>pom</packaging>
<version>1</version>
<groupId>com.jc</groupId>
<modules>
    <module>restaurant-management-core</module>
    <module>restaurant-management-api</module>
    <module>restaurant-management-rest</module>
</modules>

Comment: Spring has trouble... what does that mean? Where is the error message? And if that red line is what you mean (which is not Spring - it is a compilation error) then just hover your mouse over it and see what it says
Comment: @JAsgarov Added poms and IntelliJ error message. Please let know if I'm lacking some dependencies between modules.
Comment: you need to define spring only once in `restaurant-management/pom.xml`. Child modules will automatically have access to it. Right now you have 3 different spring dependencies all with different spring container. For further reference: https://www.baeldung.com/spring-boot-multiple-modules
Comment: @JAsgarov thanks for the advice ! I did so but it didn't solve my issue with Beans not being available
Comment: please show your updated `pom.xml`s
Answer: Actually I see already what the problem is - you have defined several modules but modules dont see classes defined in another module by default. RestaurantService is in another module from Controller
You need to add module as a dependency to the other modules pom. Intellij should suggest you to help with that if you just press "Alt+Enter" over the red line.
You might also need to make sure to set up Spring in parent pom to make sure that it spans over all modules.

Autowiring Spring Beans by Interface


How do you level Athletics in Cyberpunk 2077?

Question: Most of the traits are no brainers to level. Athletics feels like a different beast however. I looked it up and it said running around and exhausting stamina levels it but I haven't noticed it working.
The only reliable thing so far is finding 'Force Open' options on shutters and doors. Is there anything else I could do to raise it?
Answer: Punching, dashing, climbing, jumping, sliding and running will all level the athletics skill. As long as its hitting your stamina, it should be working towards more athletics experience.
With punching, you don't have to hit anything. Sliding is achieved by crouching while running. Dashing is achieved by double tapping a direction (or double tapping crouch while moving in a direction).
Having the double jump leg mods and using liberal use of the double jump and parkour actions available in the game will also help you get around while levelling up your athletics.
Dashing in particular will give regular experience for the number of times you need to dash each time - in my last playthrough I found myself dashing constantly around whoever I was supposed to be following during all of the "walking" sequences rather than trying to walk and this gave quite a lot of experience quickly.
Comment: Thanks, I tried both answers and after about 2 hours of experimenting while questing it seems that those actions do increase the skill, but you have to do it a certain amount of times before being given a chunk of exp. Which is why I wasn't noticing it before. Much appreciated.
Answer: Based on personal experience, it's a difficult skill to level. You have to run for a certain amount of time (~30 seconds) without breaks, and jumping or sliding (by crouching while running) help. Effectively, you have to treat it like a parkour game and find new ways to quickly move around. Jumping onto and off benches or low walls seems to help too, as it becomes easier to run uninterrupted if you can get just above most of the crowds.
I've also found that the risky behavior of bringing a fist to a gun fight helps cross-train the skill with street brawler, because I'll be running and sliding between cover and my next opponent, but it's much slower than focusing on running itself. The short answer is stop using a car or fast travel and just run everywhere.
Answer: It is almost certainly bugged at the moment: you'll want to, at the least, avoid perks that reduce stamina drain and possibly look into levelling glitches for this: I'm currently level 46, spent a lot of time travelling on foot and fighting with hands, and it's only level 4.
Comment: What level is your "body" at?


Customizing christmas light strings

Question: Generally, when hanging my christmas lights, I run a line around the gutters on my second floor.  From there, I drop down and put a string across the roof line on the front porch of my house.
This year, I got all new strings of lights.  The problem is that the string from the top of the roof ended in an awkward place in the line (about 2/3 of the way through the line).  So, I could essentially either "double up" a section of the upper gutter, and then run an extension cord down to the lower roof line, or I could run the lights between the 2 points, stringing the 2 sections together.  I chose to run the lights between the two points, but I don't really like the way it looks.
I could just place some electrical tape over the lights that I do not want to see, but I want a better solution.  What I want is to remove the bulbs, and replace them with just some caps which fill the bulb sockets but do not light up.  The problem is, I haven't ever seen anything like that.
Does anyone have any better ideas for customizing the length or placement of bulbs on a christmas light string?
Answer: You want to get these blackout caps.
Answer: Some light sets allow you to darken individual sections by removing one bulb in that section: I guess that's not the case with your lights, otherwise you'd already have done it.
It sounds as if the lights are in a C shape and you want something more symmetric.  A few suggestions:

get more lights and close in the opening of the C so you have lights going between the porch and roof line on both sides of the house.
use other architectural features on the upstairs (windows, etc.) or on the roof (dormers?) to use up the excess on the upstairs string.
run some of the string up the edge of the roof, using the same amount on both sides.
if you have a gutter upstairs, hide some of the excess string behind it.
Answer: Mini bulbs are 2.5v each so a 100-lt string has two 50-lt strings wired together, allowing an easy 50-50 split. To make a custom string, count the resistance of each bulb as 7 ohms and replace them with a resistor from Radio Shack. For example, to remove 20 bulbs, use a 140 ohm (20bulbs x7ohms) resistor but watch the size; the voltage drop across the resistor will be 120v/50bulbsx20bulbs=40V, which is a power consumption of about 8 watts (40Vx0.2A).
Comment: This is good method.  I agree.
If you put less resistance the bulbs are brighter, but don't last as long.
Answer: Speaking of customizing, I needed C7 bulbs at 2ft spacing for luminaries so I picked up some strings from Home Depot that have 2-part sockets and removed every other one. Of course I broke 6 before discovering how to separate them: The sockets are simple snap-together plastic with small brass fangs that tap the wire. The base has two plastic prongs that snap into the socket and hold the assembly together. Simple prying tends to break the prongs so I made a small wooden punch that can push on both prongs at the same time and used a heat gun to warm the plastic base before simultaneously pushing the base over the punch and prying the bottom off with a small screwdriver. Presto! I either have a lot of bases and bulbs left over or I can remount them on another wire.

Customizing christmas light strings


How to add a new line in a String Builder

Question: I'm trying to print a menu with string builder where after each option is printed i want to print a new line but I'm unsure why %n isn't working here. It just outputs "%n" as part of the string all on a single line. menu[] has been defined already. For the exercise i'm doing i need to do it without using regular expressions.
 StringBuilder menuText = new StringBuilder(" 0: " + menu[0] +
            "%n 1: " + menu[1] +
            "%n 2: " + menu[2] +
            "%n 3: " + menu[3] +
            "%n 4: " + menu[4] +
            "%n 5: " + menu[5]);

Comment: Take a look at the section for "Escape Sequences" [here](https://docs.oracle.com/javase/tutorial/java/data/characters.html): "_A character preceded by a backslash (\) is an escape sequence..._"
Comment: There are two good answers. Please consider supporting the community by checking one.
Answer: This answer is supplemental to "as nerdy as Steve Wozniak"'s.
The way you (OP) have used StringBuilder defeats the purpose of its fluency nature and data representation. It was introduced because of the immutability of String, i.e., appending to a String creates a new String. StringBuilder provides a way of representing a mutable sequence of characters. Here is the docs.
Instead of appending a string with +, you can make calls to StringBuilder#append.
StringBuilder menuText = new StringBuilder()
    .append(" 0: ").append(menu[0]).append('\n')
    .append(" 1: ").append(menu[1]).append('\n')
    .append(" 2: ").append(menu[2]).append('\n')
    .append(" 3: ").append(menu[3]).append('\n')
    .append(" 4: ").append(menu[4]).append('\n')
    .append(" 5: ").append(menu[5]);

Answer: You can use \n, like this:
 StringBuilder menuText = new StringBuilder(" 0: " + menu[0] +
            "\n 1: " + menu[1] +
            "\n 2: " + menu[2] +
            "\n 3: " + menu[3] +
            "\n 4: " + menu[4] +
            "\n 5: " + menu[5]);

Comment: You can use `System.lineSeparator()`.  It returns `\n` for Linux, `\r\n` for Windows like `%n`.
Comment: @RyanHolmes `\n` is not a regular expression, it's a character.
Comment: Thank you for your response but \n is a regular expression , the exercise i'm doing tells me to do it without using regular expressions.
Comment: Oh thanks, just to be sure there's no other way to do this without using \n right?


Show that $\sum\limits_{n=1}^{\infty}\left(\frac{a_{n+1}}{a_n}-1\right)$ converges.

Question: $(a_n)$ is a sequence of strictly increasing positive numbers and has a lower as well as an upper bound. The question is, if the partial sum:
\begin{align*}\sum\limits_{n=1}^{k}\left(\frac{a_{n+1}}{a_n}-1\right)&=\left(\frac{a_{1+1}}{a_1}-1\right)+\left(\frac{a_{2+1}}{a_2}-1\right)+\cdots +\left(\frac{a_{k+1}}{a_k}-1\right)\\&=\frac{a_2}{a_1}+\frac{a_3}{a_2}+\cdots +\frac{a_{k+1}}{a_k}-k.\end{align*}
converges? Because $(a_n)$ is a sequence of strictly increasing positive numbers, we have $a_{n+1}>a_n$ for all $n$. Because $(a_n)$ is bounded, we have an upper bound, e.g. $a$, and a lower bound, e.g. $b$, such that $b \leq a_n \leq a$ for all $n$. This means that $b \leq a_n < a_{n+1} \leq a$...
The problem with that is: if $k \rightarrow \infty$, then the series diverges, because of the $-k$ at the end of the expression?! Is there some kind of trick or something to use here?!
Thanks for your help in advance.
Best Regards,
Ahmed Hossam
Comment: Note that the sequence $(a_n)$ converges since it is increasing and bounded above. Hence, the fractions $\frac{a_{n+1}}{a_n}$ tend to $1$ so that your summands $\frac{a_{n+1}}{a_n}-1$ tend to $0$. Hence, the "$-k$" is not a problem. Of course summands tending to zero is just a necessary, not a sufficient condition for the series to converge.
Comment: You mean
$\lim\limits_{n \rightarrow \infty} \left(\frac{a_{n+1}}{a_n} - 1\right) = \lim\limits_{n \rightarrow \infty} \frac{a_{n+1}}{a_n} - \lim\limits_{n \rightarrow \infty} 1 =  \frac{\lim\limits_{n \rightarrow \infty} a_{n+1}}{\lim\limits_{n \rightarrow \infty} a_n} - 1 = \frac{a}{a} - 1 = 1 - 1 = 0 $
?

Is this the same as  $\lim\limits_{k \rightarrow \infty} \sum\limits_{n=1}^{k}\left(\frac{a_{n+1}}{a_n}-1\right)$?
Comment: $$\sum\limits_{n=1}^{k}\left(\frac{a_{n+1}}{a_n}-1\right)=\underbrace{\left(\overbrace{\frac{a_{1+1}}{a_1}}^{>1}-1\right)}_{>0}+\underbrace{\left(\overbrace{\frac{a_{2+1}}{a_2}}^{>1}- 1\right)}_{>0}+\cdots +\underbrace{\left(\overbrace{\frac{a_{k+1}}{a_k}}^{\rightarrow 1} -1 \right)}_{\rightarrow 0}$$

if the terms in the sum converge to $0$, does this mean that, the partial sum converges to something???
Comment: The partial sums are increasing and bounded from above... $$\sum_{n=1}^k \left(\frac{a_{n+1}}{a_n} -1 \right) = \sum_{n=1}^k \frac{a_{n+1}-a_n}{a_n} \le \sum_{n=1}^k \frac{a_{n+1}-a_n}{a_1} = \frac{a_{k+1}-a_1}{a_1}$$
Comment: The last equality is not clear...
Comment: now it's clear.
Comment: @achillehui why don't you just make an answer out of that comment? Because that's how it should be solved, I think.
Comment: @achillehui why exactly is the sequence of the partial sums increasing?
Comment: see details in answer.
Answer: You can check that it is equivalent to determine whether the series of $\log\left(\frac{a_{n+1}}{a_n}\right)$ converges, because $\frac{a_{n+1}}{a_n} \rightarrow 1$.
Edit: to be more clear:
$\frac{a_{n+1}}{a_n}-1 \sim \log\left(\frac{a_{n+1}}{a_n}\right) > 0$ as $n$ goes to infinity.
Thus, the series $\sum_n{\frac{a_{n+1}}{a_n}-1}$ is convergent iff the series $\sum_n{\log\left(\frac{a_{n+1}}{a_n}\right)}$ is convergent.
Comment: You mean $\lim\limits_{k\rightarrow \infty}\sum\limits_{n=1}^{k}\left(\frac{a_{n+1}}{a_n}-1\right) \Leftrightarrow \lim\limits_{k\rightarrow  \infty}\sum\limits_{n=1}^{k} \log \left(\frac{a_{n+1}}{a_n}\right)$?
Comment: No. I mean that one series grows to $\infty$ iff the other does.
Comment: Ok, which series is that one series and which is the other?
Comment: $\frac{a_{k+1}}{a_k} \rightarrow 1$ as $k \rightarrow \infty$, because the sequence $(a_n)$ has an upper bound. But this is only one term in $\displaystyle\frac{a_{2}}{a_1} + \frac{a_{3}}{a_2} +\cdots + \frac{a_{k+1}}{a_k}-k$. All other fractions are $>1$, because $a_{n+1}>a_n$ ...
Comment: $$\sum\limits_{n=1}^{k}\left(\frac{a_{n+1}}{a_n}-1\right)=\underbrace{\left(\overbrace{\frac{a_{1+1}}{a_1}}^{>1}-1\right)}_{>0}+\underbrace{\left(\overbrace{\frac{a_{2+1}}{a_2}}^{>1}- 1\right)}_{>0}+\cdots +\underbrace{\left(\overbrace{\frac{a_{k+1}}{a_k}}^{\rightarrow 1} -1 \right)}_{\rightarrow 0}$$

if the terms in the sum converge to $0$, does this mean that, the partial sum converges to something???
Comment: NO !! This is one of the easiest mistakes to make when dealing with converging series. Take for instance $a_n=n$ to disprove this claim in general.
Comment: A partial sum of the series based on the sequence $a_n = n$ ist $1+2+3+4+...+k$. The last term does not go to $0$ as above... What claim do you mean?...
Comment: I mean: if $a_n=n$, $\frac{a_{n+1}}{a_n}-1=n^{-1}$ so the sum of all $\frac{a_{n+1}}{a_n}-1=n^{-1}$ is infinite.
Comment: Ok, now I see the big mistake.

What does $\color{red}{\text{this}}$ mean:

$\frac{a_{n+1}}{a_n}-1 \color{red}{\sim} \log\left(\frac{a_{n+1}}{a_n}\right) > 0$

??
Answer: We are given

$(a_n)$ is a strictly increasing sequence
of positive terms
bounded from above.

Let's say $M$ is an upper bound. (*1) and (*2) implies for all $n$,
$$a_{n+1} > a_n > 0 \implies \frac{a_{n+1}}{a_n} > 1 \iff \frac{a_{n+1}}{a_n} - 1 > 0$$
As a sequence indexed by $k$, the partial sums $s_k \stackrel{def}{=}\sum\limits_{n=1}^k \left(\frac{a_{n+1}}{a_n} - 1\right)$ is a sum of positive terms, so it is strictly increasing. More precisely, we have
$$
s_{k+1} - s_{k} =
\sum\limits_{n=1}^{k+1} \left(\frac{a_{n+1}}{a_n} - 1\right)
-
\sum\limits_{n=1}^{k} \left(\frac{a_{n+1}}{a_n} - 1\right)
= \frac{a_{k+2}}{a_{k+1}} - 1 > 0
\implies s_{k+1} > s_{k}
$$
By (*1) and (*2) again, we have $a_{n+1} > a_n \ge a_1 > 0$. This implies
$$s_k = \sum_{n=1}^k \left(\frac{a_{n+1}}{a_n} - 1 \right)
= \sum_{n=1}^k \frac{a_{n+1} - a_{n}}{a_n}
\le \sum_{n=1}^k \frac{a_{n+1} - a_{n}}{a_1}
= \frac{1}{a_1}\sum_{n=1}^k (a_{n+1} - a_n)
$$
The last sum is a telescoping sum. Together with (*3), we obtain
$$s_k \le \frac{1}{a_1}(a_{k+1} - a_1) \le \frac{M-1}{a_1}$$
This means as a sequence, the partial sums is bounded from above too.  Being increasing and bounded from above, the sequence $s_k$ converges. By definition, so does the series
$\sum\limits_{n=1}^\infty \left(\frac{a_{n+1}}{a_n} - 1\right)$.


In a gradle plugin, how do I replace maven plugin 'uploadArchives' with artifactory plugin 'artifactoryPublish'?

Question: Yes, I do need to apply both the 'maven' and 'artifactory' plugins.  However, there are many, many existing Jenkins jobs which explicitly call 'uploadArchives' (supplied by the maven plugin).  I would like to override that in my own plugin to force it to call 'artifactoryPublish' when 'uploadArchives' is used.
I want to do this programmatically in my plugin, rather than changing hundreds of build.gradle files, and I have tried every combination of calls I can think of with no luck so far.
The last caveat is that this has to work back to Gradle 2.4 at a minimum, as the gradle wrapper is being used and several different versions of gradle are invoked over a set of builds.
Anyone have an idea on how to accomplish this?
Here's the latest thing I tried:
project.getTasks().replace('uploadArchives', MyTask)
Although the constructor is called (verified by a println message), the task itself is never called (verified by adding an explicit 'throw' statement and never seeing the exception).
Comment: Do you necessarily have to override the task? Would supplement work?
Comment: Also, once you succeed in building your plugin, don't you have to then add your plugin to the hundreds of build.gradle files?
Comment: I don't want anyone to use uploadArchives any longer, but there are possibly a few hundred existing automated jobs which call it.  So it would be helpful if the jobs called my stuff instead, without having to change all those jobs.  As for adding my plugin, that's already being done - I'm just changing implementation.
Answer: Just to clarify...
I want to override uploadArchives for 3 main reasons:

Many existing jobs (as well as programmer's fingers) with
uploadArchives programmed in.
We WANT the extra info artifactoryPublish creates and uploads,
especially if done via the Jenkins plugin, so you get Jenkins job
number, etc.
We do NOT want anyone using plain uploadArchives and publishing
WITHOUT the extra build info.

I finally found the answer myself... it's not exactly straightforward, but does work as we wished, except for the extra output line about uploadArchives during a build.
<code>    project.plugins.apply('com.jfrog.artifactory')
    project.getTasks().create([name: 'uploadArchives', type: MyOverrideTask, overwrite: true, dependsOn: ['artifactoryPublish'] as String[], group: 'Upload'])
</code>
Yes, I could have just disabled uploadArchives after making it depend on artifactoryPublish, but then instead of just printing 'uploadArchives' during the build, it prints 'uploadArchives [Skipped]', and we didn't want there to be any confusion.


Javascript iterate through nested Object and return transformed and renamed Array of objects

Question: I've checked out all available answers regarding nested objects but none helped so far.
I do have a deep nested object like:
let datastat =
{
  "statisticData": {
    "lastStatisticOne": {
      "min": 0,
      "max": 10
    },
    "lastStatisticTwo": {
      "min": 0,
      "max": 20
    },

    "firstStatisticOne": {
      "min": 0,
      "max": 30,
    },
    "firstStatisticTwo": {
      "min": 0,
      "max": 40,
    },
  },
  "statisticValue": [
   none important Data
  ]
}

What I try to achieve is:
statisticNew =
[
  {
   "lastStatisticOne": [{ "name": "min", "value": 0 }, { "name": "max", "value": 10 }]
  },
  {
   "lastStatisticTwo": [{ "name": "min", "value": 0 }, { "name": "max", "value": 20 }]
  },
  {
   "firstStatisticOne": [{ "name": "min", "value": 0 }, { "name": "max", "value": 30 }]
  },
  {
   "firstStatisticTwo": [{ "name": "min", "value": 0 }, { "name": "max", "value": 40 }]
  }
]

My attempt failed:
const statistic = [];
statistic.push(datastat.statisticData);

for(let item in statistic){
 if (statistic.hasOwnProperty(item)) {
  const result = Object.keys(statistic[0]).map(e => ({name: e, value: statistic[0][e]}));
  console.log(result);
 }
}

How can I achieve the correct output?
Comment: https://jsfiddle.net/khrismuc/qfu1n5gc/
Answer: This should do it:
let datastat = {
  "statisticData": {
    "lastStatisticOne": {
      "min": 0,
      "max": 10
    },
    "lastStatisticTwo": {
      "min": 0,
      "max": 20
    },

    "firstStatisticOne": {
      "min": 0,
      "max": 30,
    },
    "firstStatisticTwo": {
      "min": 0,
      "max": 40,
    },
  }
}

let newStat = Object.keys(datastat.statisticData).reduce((acc, key) => {
  let vals = Object.entries(datastat.statisticData[key]).map(([key, val]) => ({
    name: key,
    value: val
  }))
  acc.push({
    [key]: vals
  });
  return acc;
}, []);

Answer: This is the Solution provided by Chris G and works perfekt. Thank you!
const statisticNew = Object.entries(datastat.statisticData).map(([key, val]) => ({
  [key]: Object.entries(val).map(([name, value]) => ({ name, value }))
}));

Answer: You can iterate over the keys of your dataStat and get your expected output like below :
                let statisticNew = [];
                Object.keys(datastat['statisticData']).map(function (item) {
                  let stat_obj = {};
                  let temp_arr  = [];
                  let inner_dict = datastat['statisticData'][item];
                  Object.keys(inner_dict).map(function (inner_item) {
                      let temp_obj = {};
                      temp_obj['name'] = inner_item;
                      temp_obj['value'] = inner_dict[inner_item];
                      temp_arr.push(temp_obj)
                  });
                  stat_obj[item] = temp_arr;
                  statisticNew.push(stat_obj);
                });
                console.log(statisticNew)

Answer: You can first reduce value using reduce function and then mapping it accordingly. Here is how:

var datastat = { "statisticData": { "lastStatisticOne": { "min": 0, "max": 10 }, "lastStatisticTwo": { "min": 0, "max": 20 }, "firstStatisticOne": { "min": 0, "max": 30, }, "firstStatisticTwo": { "min": 0, "max": 40, }, }, "statisticValue": []};

reducedValue = Object.entries(datastat.statisticData).reduce((acc, [key, value])=>{
  acc[key] = acc[key] || [];
  for(const [k, v] of Object.entries(value)){
     acc[key].push({name : k, value :v})
  }
  return acc;
},{});

var result = Object.entries(reducedValue).map(([k,v])=>({[k]:v}));
console.log(result)


Pathtracing line and point primitives?

Question: So I'm in the midst of implementing a path-tracer. I have chosen to use Assimp library to load models and scene information.
According to it, it will provide mesh data and meshes may contain point, line, triangles and polygons primitives. It gives the option to triangulate polygons but I don't know what to do with lines and points. Should I ignore them?
This leads to a bigger question that came in my mind. Can we ray-trace points and lines? I wanted to use this kind of thing once to show my Bounding boxes in wire frame mode but didn't know how I would trace only the boundaries.
I'm guessing this has to do with providing a specific line/point width? Else they are too thin for intersection.
If we can render lines and points, then should I ignore them or not in my path tracer? Will I be missing out on details etc? Don't know what are they used to represent in 3D models as I have only seen triangles/polygons.
Answer:
I'm guessing this has to do with providing a specific line/point width? Else they are too thin for intersection.

Exactly. True points and lines have no spatial extent: a point is infinitely small, a line is infinitely thin. You can't intersect those with a ray. But a point with a size is just a sphere, and a line with a size is a cylinder, and those are classic ray-casting primitives, so of course you can intersect them.
The only difficulty is if your path-tracer currently only has one geometry primitive (the polygon or polygon mesh): adding new primitives might be hard for you, if you've structured it for just one. But even in that case, instead of intersecting the points and lines directly, you can just turn them both into polygon meshes inside the renderer, before casting any rays. If you know how to polygonise a sphere and a cylinder you already know what to do.
Comment: I haven't actually written the model loading part at all so I'm still open to ideas. My main approach was to load any model/scene through assimp and set a post processing option which "triangulates" anything having more than 3 indices. This assures I only need to check for ray-triangle intersection. However according to assimp it won't modify lines and points.

Thus I wanted to know if ignoring these points and lines would make any real difference to the appearance of the model?
Comment: @wandering-warrior That depends on the particular model and the format you're loading. Try it on some models you're interested in and see what happens. Chances are they won't contain any points or lines anyway.

Pathtracing line and point primitives?


How much can I turn before losing bonus movespeed?

Question: The new champion Aurelion Sol's ability Comet of Legend states he

gains Escape Velocity while moving, up to 100. He also gains bonus
  movement speed, based on how long he's been moving in the same
  direction.

My question is how much can I turn and still be considered moving in the same direction? Is there a certain amount of degrees of rotation I may turn before losing all my bonus movespeed?
Answer: If you break it down, the method of how the passive is working is based off of the physics formula of velocity + speed in a single direction. If you change direction even slightly, some of the velocity is lost. You completely change direction, the velocity in that direction is completely gone. Check out this link for a better explained way.
Your bonus movement speed is lost when you make a sharp turn; 45 degrees, 90 degrees etc. The best way to use the passive of Aurelion's travel is to always go directly straight. Even small turns can cause you to lose a bit of movement speed.
At best, you should practice with trying to hold onto as much escape velocity as possible while maintaining turns in the game to get a better angle at viewing and maintaining it. You might even get an edge on how to maintain it during skirmishes and team-fights, and that knowledge would be very advantageous for you and your team.
Answer: It's around 20 degrees from your face. An L turn drops your speed quite fast.


fql.multiquery doesn't work as expected

Question: $pairs = $facebook->api(array(
        'method' => 'fql.multiquery',
        'queries' => array(
            'query1' => 'SELECT uid1 FROM friend WHERE uid2 = me()',
            'query2' => 'SELECT uid1, uid2 FROM friend WHERE uid1 IN (#query1) AND uid2 IN (#query1)'
        )
));

That gives me a Parser error: unexpected '#query1' at position 45. error, which I don't understand. I thought the above was exactly how it was supposed to work?
Answer: The proper way to build query2 is
SELECT uid1, uid2 FROM friend WHERE uid1 IN (SELECT uid1 FROM #query1) AND uid2 IN (SELECT uid1 FROM #query1)
But overall this call is inefficient. The request will fail because it's too resource intensive. You're probably going to have the break up the second call per friend.

fql.multiquery doesn't work as expected


Streamlined way to do C# run-time type identification that avoids a NULL check?

Question: I find myself using a common run-time type identification pattern, especially when writing code that handles controls of varying types.  Here is the pattern:
if (ctrl is ControlTypeEtc)
    (ctrl as ControlTypeEtc).SomeMethod();

I do this to avoid having to do a NULL check in case the as operator returns NULL.  Is there a way to streamline this to a single operation?
Comment: Using 'as' with null check is as streamlined as you will get.
Comment: See my suggestion below, use the Pre-processor:
Answer: No way to do this in a single operation.
However, using as and checking for null is cheaper as there is only one case instead of two as in your code sample.
Comment: Keep in mind that this is more superior to the original code snippet you pasted not only because it does one cast, but also because it deals with situations where `ctrl` is a derivative of `ControlTypeEtc`
Answer: I would write it as:
ControlTypeEtc ctrl2 = ctrl as ControlTypeEtc;
if (ctrl2 != null)
    ctrl2.SomeMethod();

That avoids the double check (which may be optimized into one but I'm not sure).
Another way:
try
{
    ControlTypeEtc ctrl2 = (ControlTypeEtc)ctrl;
    ctrl2.SomeMethod();
}
catch (InvalidCastException e)
{
}

Answer: Bottom line is, "Big picture" you should know if your instance is null before you proceed coding against it.  there really is no reason to find a shortcut around that step.
That said, if you are using C# 3 or better you have Extensions methods which can be used to "hide" this detail from the main logic of your code.  See below the sample with 'SomeType' and 'SomeMethod' and then an extension method called 'SomeMethodSafe'.  You can call 'SomeMethodSafe' on a Null reference without error.
Don't try this at home.
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            SomeType s = null;
            //s = new SomeType();
            // uncomment me to try it with an instance

            s.SomeMethodSafe();

            Console.WriteLine("Done");
            Console.ReadLine();
        }
    }

    public class SomeType
    {
        public void SomeMethod()
        {
            Console.WriteLine("Success!");
        }
    }

    public static class SampleExtensions
    {
        public static void SomeMethodSafe(this SomeType t)
        {
            if (t != null)
            {
                t.SomeMethod();
            }
        }
    }
}


How much thinset is enough?

Question: I'm having a shower tiled and I noticed that the tiler didn't put thinset over the entire area, just on the back of individual tiles.
The tiles are heavy stone 3/8x6x12. He used a 1/2 x 1/2 trowel to apply the thinset. It looks like he put just enough in the middle of the back of the tile to keep it from smooshing out to the edges instead of applying it to the Durock® and pressing the tile into it.
Is this normal?
Answer: The purpose of the thinset is to secure the tile to the substrate (the Durock in this case).  So if the tile stays on the wall, I suppose you could say it is enough, but I don't think that is what you are asking.
I am no tile pro but my understanding is that you want to have at least 90% coverage on the back of the tile once it is pressed into the wall.  The only way to really test this is while laying the tile and try it out. Push the tile onto the wall and then pull it off again, is there thinset on almost the entire back surface of the tile (and the trowel's pattern is no longer visible)?
Applying thinset directly to the back of the tile is called "back buttering" and is a very common technique with large format tiles and natural stone. I think it is usually combined with troweling thinset onto the wall (or floor) and is not a replacement for it (but I am not real sure about that).
1/2 x 1/2 notch trowel seems fine, when I did our shower with 8x12 porcelain tile I used a 3/8 x 3/8.  If the installer was only back buttering the tile in the middle but troweled it out so almost the tile's entire backside was covered with the 1/2" notch pattern of thinset that is OK; it will work just as well so doing that same thing on the wall.
All that really matters is if there is enough thinset on the backs of the tiles.  If the installer only dabbed a little thinset in the middle of the tile, they will not be as securely attached compared to if the whole tile was covered. Without knowing exactly what the coverage on the back of the tile, it is impossible to guess if you tile is fine and will last for many years or if they may fail premature because they were not secured to the wall well enough.
Comment: You're right that "back-buttering" is supposed to supplement thinset on the surface to which the tile should adhere, and not replace it. By back-buttering using a notched trowel, you allow yourself to level the tile relative to others; you get a "thick" layer of thinset to work with, while minimizing situations in which you lay too much thinset and it starts oozing between tiles (though that does still happen, usually as you "float" the tile into proper alignment).
Comment: That might have been why he used a 1/2" x 1/2" notch so that he had a nice "thick" layer of thinset.

How much thinset is enough?


Linq to SQL to ObservableCollection for treeview in VB.Net

Question: I have some Linq to SQL table classes that are joined together. I currently have it bound to a treeview using just the LINQ to SQL query. It works, but it doesn't show when stuff is added or removed from the database.
I implemented INotifyPropertyChanged but it isn't updating the treeview.
I also tried using Bindable Linq, but it doesn't seem to make a difference.
I found an example of a way to easily create ObservableCollections without having to create more classes: jimlynn.wordpress.com/2008/12/09/using-observablecollection-with-linq/, (which is kind of important because I have a future project looming that will require interacting with a lot of tables (30 or so) and just creating the Linq to SQL classes is going to be a pain).
    Property ModelQuery As ObservableCollection(Of dbModels) = New ObservableCollection(Of dbModels)().PopulateFrom(From mm In tblModels.AsBindable Order By mm.ModelName)

Is this a good way to go, or am I going to have to create a separate ObservableCollection and maintain them both in code. If I'm going to use this binding stuff,  I'm really looking for a way to have stuff just linked together so I don't have to update multiple structures whenever a change is made.
Main table:

 Public Class dbModels
    Implements INotifyPropertyChanged
    Private _changed As Boolean
    Public Event PropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
    Protected Overridable Sub OnPropertyChanged(ByVal Propertyname As String)
        If Not Propertyname.Contains("Changed") Then
            Changed = True
        End If
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(Propertyname))
    End Sub
    Public Property Changed() As Boolean
        Get
            Return _changed
        End Get
        Set(ByVal value As Boolean)
            If _changed <> value Then
                _changed = value
                OnPropertyChanged("Changed")
            End If
        End Set
    End Property

    Private _ModelID As Integer
    <Column(Storage:="_ModelID", DbType:="int IDENTITY NOT NULL", IsPrimaryKey:=True, IsDbGenerated:=True, Name:="ModelID")> _
    Public Property ModelID() As Integer
        Get
            Return Me._ModelID
        End Get
        Set(value As Integer)
            Me._ModelID = value
        End Set
    End Property

    Private _ModelName As String
    <Column(Storage:="_ModelName", DbType:="Varchar(200)", Name:="ModelName")> _
    Public Property ModelName() As String
        Get
            Return Me._ModelName
        End Get
        Set(value As String)
            Me._ModelName = value
        End Set
    End Property

    Private _ModelYears As EntitySet(Of dbModelYears) = New EntitySet(Of dbModelYears)
    <Association(Storage:="_ModelYears", DeleteRule:="CASCADE", OtherKey:="ModelID")> _
    Public Property ModelYears As EntitySet(Of dbModelYears)
        Get
            Return _ModelYears
        End Get
        Set(value As EntitySet(Of dbModelYears))
            _ModelYears.Assign(value)
        End Set
    End Property

End Class

Joined table:

 Public Class dbModelYears
    Implements INotifyPropertyChanged
    Private _changed As Boolean
    Public Event PropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
    Protected Overridable Sub OnPropertyChanged(ByVal Propertyname As String)
        If Not Propertyname.Contains("Changed") Then
            Changed = True
        End If
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(Propertyname))
    End Sub
    Public Property Changed() As Boolean
        Get
            Return _changed
        End Get
        Set(ByVal value As Boolean)
            If _changed <> value Then
                _changed = value
                OnPropertyChanged("Changed")
            End If
        End Set
    End Property

    Private _ModelYearID As Integer
    <Column(Storage:="_ModelYearID", DbType:="int IDENTITY NOT NULL", IsPrimaryKey:=True, IsDbGenerated:=True, Name:="ModelYearID")> _
    Public Property ModelYearID() As Integer
        Get
            Return Me._ModelYearID
        End Get
        Set(value As Integer)
            Me._ModelYearID = value
        End Set
    End Property

    Private _ModelID As Integer
    <Column(Storage:="_ModelID", DbType:="int", Name:="ModelID")> _
    Public Property ModelID() As Integer
        Get
            Return Me._ModelID
        End Get
        Set(value As Integer)
            Me._ModelID = value
        End Set
    End Property

 Private _ModelYear As String
    <Column(Storage:="_ModelYear", DbType:="Varchar(50)", Name:="ModelYear")> _
    Public Property ModelYear() As String
        Get
            Return Me._ModelYear
        End Get
        Set(value As String)
            Me._ModelYear = value
        End Set
    End Property

End Class

Answer: Implementing INotifyPropertyChanged or using ObservableCollection wont notify you of changes in the database. You are going to have to execute the query every time you want to retrieve new data from the database.
Alternatively you could possibly use SqlDependency to set up a query notification dependency between your application and an instance of SQL Server.
EDIT:
From comments.
To hook up the PropertyChanged event of the items in the collection.
For Each item As var In itemsCollection
    Dim notifyItem = TryCast(item, INotifyPropertyChanged)
    If item IsNot Nothing Then
        AddHandler notifyItem.PropertyChanged, AddressOf ItemChanged
    End If
Next

Public Sub ItemChanged(sender As Object, e As PropertyChangedEventArgs)
  'Handle event
End Sub

Comment: Does that mean that it won't notify me if I make changes in the instance I'm running, or that it won't notify me if someone else makes changes to the database from another computer? Is there a reason it wouldn't see the changes if I trigger the property changed in the class?
Comment: It wont notify you of changes made in the database. If you make in memory changes to the `ObservableCollection` it will notify you.
Comment: Is there a reason it's not notifying me then? Would it make a difference if the change was made in a child class that's joined with an entityset?
Comment: If you want notification of changes to the items inside the collection you are going to have to iterate over the collection add hook of the events.
Comment: Ok, that sounds reasonable... pointers on where to start looking for info so I can learn that? I'm still pretty noob with wpf in some areas.
Comment: Definitely looks interesting... just trying to figure out how to apply it to my case. Does the for loop fit into the Linq class, or does it belong outside of the class? Sorry I'm slow at this.


TDS Endless waves of Rebel Spies?

Question: In what has to be the furthest from complaining I can be, I noticed recently that I am getting almost exclusively Rebels arriving at my Death Star.... As in, as soon as I catch one, another comes in. Now, in the past two hours, I've taken in over seventy Imperial Bux... my question is, does anyone know what may have caused this. I don't believe in cheating, but I am also not opposed to getting a fun bonus every now and then...
Update: The massive influx ended after about a day and a half. To answer questions, no, I hadn't ignored the game, however, I noticed I was getting Rebels at what had probably been a slower pace than most (usually only one or two every six hours or so, playing in thirty minute increments).
I had the third elevator upgrade at the time, and now (because of the bux earned) have the final elevator.
I now get Rebels randomly, sometimes one after another, sometimes one with another following about 15 mins later or so.
Comment: If this was played over the holidays, and turned out not to be a backlog, it could be an event/happy new year from the developers giving out free cash, but making you earn it.
Comment: I had this happen with Lando. He arrived 7 times in a row. I had 16 levels, and I left the game for a while. I also had not upgraded my elevator. So, maybe the game was trying to help. I don't know. A couple of times he escaped, but, I could not see a reason why, since I had found him immediately after pressing the blue button.
Comment: The speed by which you find them seems to have no bearing on whether they escape or not. And, escaping is a good thing because it gives you 2 Bux instead of 1.
Comment: I get Lando over and over again too. And like others I am all of the sudden getting a high rate of both rebel spies and deliveries. I have all the levels and I'm trying to get Darth Vader to pop for a scene unlock. Instead I seem to get Lando and Bespin Leia over and over. It's annoying.
Comment: The bitizens seem to unlock in the same order for everyone. I have played the game for nearly 2 months without unlocking Darth Vader. And, I still have a number of species to unlock. I think they unlock on their own time regardless of the missions.
Comment: I've observed a sharp increase in the frequency of rebel and find the bitizen events too. My spouse has also. We both have Android phones.
Comment: Did u guys ignore your Death Star over the holidays or anything? I'm just wondering if this is backlog.
Comment: Same here (iOS). I didn't count, how much time it took, but I certainly made more than 70 bux last night. And day after that night it is still happening. Quite annoying, I'd say. I have 58 levels, so finding them isn't easy. And it's hard to stop yourself from doing it, too, despite the fact that I still need to fill 1,5 residential levels...
Comment: I live in a different timezone, for me it was happening from the night of the 2th till 4th. I can't say I'm a very active player - I mostly was only stocking levels, and I was catching spies, if they showed up. But I didn't open the app less than 5 times a day. Of course, I started hunting spies actively when this started. Now there are a bit less bux quests than two days ago, but they still appear once in five minutes or less, which is more frequent, than in last year. (sorry for my English)
Comment: Well, no, I take my words back: they appear muuch more frequently, than once in five minutes. Also I just saw Luke hanging out on of the levels while I was looking for Lando. I thought it was the next quest, which has already appeared (the icon already was on the bottom of my screen), but the next quest was to find Chewie, and Luke disappeared.
Answer: Normally I'd tell you that this is random chance. But 70 in an hour points to some random bug in your favor. Keep playing and let us know if it changes.
I can say, though, that I have seen a large number of these missions in a row when I've put down the game for a while. It seems they build up over time, and if you don't play they come out all at once.
This seems harmless.  My only concern would be that if it is not progressing past a certain point, things may not be unlocking.  But, if everything else seems normal, sit back and enjoy the Bux before your eyes get blurry from searching!
Answer: I have an Android phone and got the same increased frequency of rebels (which has now ceased).  In the last few days I managed to collect about 250 additional bux.  I think this was some sort of promotion/bonus because I got two notifications from TDS related to rebel spies during this time period.  I think the first was something like "We have detected a nest of rebel spies, keep on the lookout."  The increase in rebels occurred shortly after this.  Then a day or two later the second notification said something like, "We have uncovered the rebels hiding place, watch for an influx of spies." To answer the question raised in some of the other comments: I didn't ignore TDS during the holidays.  I played less but still checked in multiple times per day.
Comment: After my answer above I started getting more spies again so I guess there was just a lull. Yesterday I got another notification that was something like, "Keep finding rebel spies for special rewards".  Just now I got: "The Rebels are retreating! Last chance to catch spies before they're gone."  Sure sounds like a limited time bonus opportunity to me.
Comment: And today's notification: "Imperial Tech Notification: Rebel spy breach will be fixed by end of day. Stay on..."  I think it was truncated because they don't properly use expanding notifications but you get the idea.
Answer: I believe it is a help to get the 140 bucks needed to get the holiday Boba Fett and Panna City medicines/pharmacy. We only have three days left to get them both.
Comment: This seems unlikely. They would more likely give many decorator droids instead.
Answer: I think its a kind of Holidayevent - Like in MMORPGs, where you earn more xp at Halloween etc.
Its hard to stop, easy earned Bux - but a lot of time lost :)
Comment: That is wild conjecture at best.

TDS Endless waves of Rebel Spies?


pig latin FILTER and GENERATE

Question: I have a simple tuple (userid, country, amount, transactionid, date, crap1, crap2,crap3)
I am using FILTER to filter out some data and at the same time I want to drop some elements from the tuple. The reason they exist in the tuple is cause I need them at the some earlier point but not after the filter.
currently i am doing
B = FILTER A by date == 'xxxx';
C = FOREACH B GENERATE name, country, tranactionid;

Is it possible to do it in one statement (to speed up the query), because as I understand FOREACH + FILTER + GENERATE only work on nested bags.
Comment: Why you are sure that it will speed up the query while there is a powerful optimizer in Pig ? Do you check your explain plans ?
Comment: i assumed that there will be only one run through the tuples instead of 2 times
Comment: I am still figuring out how to interpret the 'explain' plans
Answer: Not possible..
FILTER alias  BY expression;

and
FOREACH { gen_blk | nested_gen_blk } [AS schema];

pig latin FILTER and GENERATE


Manipulating PDF file

Question: I would like to read a PDF file as a text (postscript), add new objects in the file structure and save the final output as a new PDF but If I just copied the PDF PostScript content and paste it in a newly created PDF file (where encoding='ansi'), the file doesn't work.
I am sure that this may be encoding issue but I am not sure what I should do to have a valid PDF file format after manipulating the original PostScript content.
Here is the piece of code that didn't work with me:
pdf_file = open('Input.pdf', 'r', encoding='ansi').read()
pdf_file_bytes = bytearray(pdf_file, 'ansi')
pdf_file = open('Output_bytes.pdf', 'wb').write(pdf_file_bytes)

And as I said, the output PDF is not valid!
Comment: This looks very much like [this question](https://stackoverflow.com/q/55260008/1729265)...
Answer: A PDF file is a complex file format consisting of various objects, unless you under low-level syntax of the PDF specification carefully it will be difficult to impossible to arbitrarily replace some bytes with some other bytes and have it result in a still valid PDF file.
More to the point what are you trying to accomplish.  E.g. there may be a high-level way of doing whatever you're trying to do that doesn't involve manipulating PDF syntax directly.  E.g. if you need to modify a font, add an annotation, set the PDF version, etc.  Otherwise if you actually need to modify PDF syntax you need to use a library capable of dealing with low-level objects.
Answer: First problem; the content of a PDF file is PDF, not PostScript.
Secondly, PDF is a binary file foramt so if you copy and paste it any kind of translation (such as CR/LF) will break it.
You haven't said what programming language your code uses, though it looks like Python. If it is Python then reading the file as binary instead of text might help.

Manipulating PDF file


How to get username and password of mysql database

Question: I am trying to connect to mysql database from java and I forgot username and password of Mysql plz help me to get username and pass.
Comment: Do you have super-user (or `mysql` user) privileges on the database machine?
Comment: yes i have that privilege..
Answer: You can't  get back your password but you can reset it:
http://dev.mysql.com/doc/refman/5.5/en/resetting-permissions.html


Retina display on iPad3 set background image using css

Question: I tried the following css, but it doesnt help on iPad3. Only one fourth of the image fits on iPad3.What is going wrong?
<code>.titleIcon {
  float: left;
  background: url(/images/sprite.png);
  background-position: 0px 0px;
  width: 16px;
  height: 16px;
}

@media
only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (   min--moz-device-pixel-ratio: 1.5),
only screen and (     -o-min-device-pixel-ratio: 3/2),
only screen and (        min-device-pixel-ratio: 1.5){

    .titleIcon{
        float: left;
        background: url(/images/sprite-2x.png) no-repeat 0 0;
        background-position: 0px 0px;
    }

}
</code>
Answer: The ipad 3 got a pixelratio of 2, so your media queries don't work yet. Add min-device-pixel-ratio: 2 to your code.
Further reading: http://halgatewood.com/ipad-3-media-query/
Comment: Maybe you should a a background size? Read this article btw: http://mikepultz.com/2012/03/how-to-make-images-look-good-on-the-ipad-3/
Comment: i set width and height to 16px . background-size property doesnt work for me even for a normal image in case of desktop browser.Still it doesnt help.The image seems too big to fit
Comment: Why does the background-size not work? According to W3Schools: "The background-size property is supported in IE9+, Firefox 4+, Opera, Chrome, and Safari 5+.".

See: http://www.w3schools.com/cssref/css3_pr_background-size.asp
Answer: Devices with a retina display use a virtual viewport where each CSS pixel is actually made up of two device pixels. If you create a div that is 100x100px, it will look the same size on a retina display as it does on a regular display, even though it's actually 200x200px on the retina display in terms of device pixels.
Usually this is a good thing, but it means your extra high resolution image is going to look just as big on the retina display as it would on a regular display (i.e. too big to fit). You'll need to scale it down to half the size, if you want the whole thing to be visible.
On a regular display, this would mean losing resolution, but because the retina display has two device pixels per CSS pixel, this cancels out and the image is shown exactly as intended.


Is updating/avoiding this splice worth it, and if so, what's the easiest way to plug the hole?

Question: An outlet was discovered to be midway through a segment of unsafe (too thin gauge for circuit, no ground) wiring. Let's refer to point A as a junction to the rest of the circuit (which is all good to go), point B as this outlet, and point C as an important outlet at the end of this branch. There's nothing else on the branch between A & C.
Because the outlet at point B was hidden by furniture and not used, and there's already ~8 other outlets on this circuit (maybe more), it's been decided that this outlet could simply be removed. To most rapidly get rid of the unsafe wiring between point A & C, new wire was pulled through each end of the gang box and spliced, thus completing the circuit with new wiring. However, this leaves an unnecessary splice in a gang box at point B, and the box itself seems a little unsafe to me (it is a not very secure/stable, old work box).
To reduce electrical risks, it seems to me it's worth it (though not high priority) to re-run a length of wire from point A to C directly with no splice, and in the process remove the old work box. This is not that difficult and since splices and rickety junction boxes are some of the major electrical hazards as I understand it, it's worth upgrading: it will take 10 feet of 12/2 NM, pull part way through from point C to B and then pull the rest of the way through from B to A and get it all hooked up.
When all that is said and done, the rickety gang box will be empty and unneeded. Easy enough to remove if that's best, it's practically falling out of place now. What's the easiest way to plug the hole? Do I need to add drywall + joint compound + paint, or can I just put a gang box cover on the empty box? Guess I'm trying to confirm if it makes sense to rewire the splice out of existence, and if there's any problem putting a cover on an empty box or even somehow putting a cover on an otherwise open but discrete hole in the wall.
Comment: The question is a bit convoluted and i do not know what you mean by " Splice " and " unnecessary splice " , if the connections are done with proper wire nuts to code then I vote for just  put a cover plate on the box and call it time and money saved.
Comment: An unused receptacle is unused.  It doesn't consume power.  It's not a load factor. It doesn't matter how many unused outlets exist.
Comment: The point is that the receptacle and its box aren't in great quality and are in a difficult spot to fit a gang box in, so since it's unnecesary it'd be better to avoid connections in loose hardware and just run a straight wire from point A to C.
Answer: In my opinion it's not worth the effort and cost to re-run the wire. As long as the inline splice is properly connected at B, e.g. using proper wire nuts, it is not considered a major hazard. Even if you "improve" it by a wire directly from A to C, it is likely you have other splices in your other circuit anyway.
In terms of cover plate vs patching drywall, that's totally up to you. If it's behind furniture, why not simply choose the easier way.
Comment: This makes sense. The box the connection is in is what worries me, as the connections themselves are as good as any other (done properly with appropriate wire nuts and even tape).
Answer: If the wire gauge is too small, you do need to replace it. The only reason I can think of code wise that the box was added would be to have no more than 12 feet between outlets or no point more than 6' from an outlet.
If you decide to remove the outlet, I would leave a service loop of wire in that location when you pull the new cable in. Remove the old work box and patch the wall. You will be able to find the spot in the future if you decide to install another outlet in the future.
You could leave the box and put a cover plate on it, and this would be legal also, but from your description it sounds like a service loop and a patch job would be the way I would go.
Answer: Do Not run afoul of rules requiring receptacles at certain spacing along the wall.  Generally any point on the wall must be within 6' of a receptacle using sensible routings, because that is how long lamp cords are.
I do not agree with the opinion that splices are a major failure point.  Whoever said that isn't very good at splices.  Use Ideal brand wire nuts in the middle of their working range, and tighten them gorilla tight.  Done.
The rickety old box is worrisome but why is it rickety?  Is it attached to only drywall?  If it's possible to attach it more firmly to the joist, I am fond of 7/8x#6 deck screws usng Torx or Robertson drive  and a little sideways ratchet driver.  You can always replace it with another old work box, but a steel box beats a plastic one any day of the week in my book.
Comment: I agree with the metal boxes they usually have wings or flanges on both sides close to full length compared to cheap plastic that just have 2 small arms. Also with wire nuts 2 full twists of the wires outside the nut is required I call this gorilla tight if done by hand but usually use a driver when doing more than a few.
Comment: Why do you recommend Ideal brand wire nuts? I have always liked Scotchloks wire nuts, perhaps because they were recommended by expert Jesse Aronstein at one time for pigtailing aluminum and I bought boxes of several sizes. "The 3M Scotchlok connector had shown the best performance in this application compared to other types of twist-on connectors." (No wire nuts are now considered acceptable for pigttailing aluminum  https://inspectapedia.com/aluminum/Twist_On_Connecrtors_Aluminum_Wire.php).
Comment: @Ed Beal what kind of driver do you use to tighten wire nuts?
Comment: Would it be acceptable to drill holes in the side of a metal box and drive screws at an angle into the stud? Or would this be a code violation as an improvised, unrated method of attachment? I believe there are plastic boxes that are designed and rated to be screwed on this way.
Comment: @JimStewart scotchloks are my nemesis. They are very, very hard to remove, involving lots of fighting, and they tend to really dislike reuse - I believe they are not even listed for reuse as the spirals are often visibly distorted after removal. The modern wisdom I am hearing is that there's been a lot of evolution in wirenut design and new designs are so much better than 20yo designs.  Most seem to regard Ideal as king of the hill. I'm sure 3M poured some sort of materials science genius into Scotchloks, that's what they do, but it's lost on me.
Comment: @JimStewart you're allowed to dril holes in metal boxes. And you're allowed  to use screws through the holes, that's what they are for.
Comment: I have a 1/4" driver/ impact and a bit that holds the wings, once the wire twists 2 full times this meets the Manfacturers requirements. After doing many thousands I was having wrist problems and found the tool, I still do them by hand if it is only a outlet or switch but roping a house and pigtailing is faster and my wrist is fine. Ideal works the best with this tool but I do also use scotchlocks tan and red and orang and blue but they don't hold as well in the tool but are a bit smaller than ideal.
Answer: Since the 6' / 12' receptacle rules are design rules, not safety rules, and violating them doesn't cause a fire or shock anyone, I wouldn't worry about it.  It can be corrected in the future if need be.
Since it's an old work box, I wonder if it was even required for the 6' rule in the first place?  Maybe if the house is older than the rule.
So I'd run new wire bypassing the middle box and be done with it.
I am not sure I'd care much about an empty box behind the couch being loose.  If you get a sturdy unbreakable blank cover, the tension from the cover screws should steady it.
You could enlarge the hole and use a double gang old work box and cover, if the new half of the box opening is tight, it won't wobble.
You could patch the drywall... a lot of work for little return IMO.


Show if $\{x_n\}$ is a Cauchy sequence in $X$ then the sequence of norms $\{\|x_n\|\}$ is a Cauchy sequence of real numbers

Question: I am trying to prove that if $\{x_n\}$ is a Cauchy sequence in $X$ then the sequence of norms $\{\|x_n\|\}$ is a Cauchy sequence of real numbers.
This is the proof:
Since $\|u_m\| - \|u_n\| \leq \|u_m - u_n\|$ the sequence is a Cauchy sequence in $\mathbb{R}$

I am not sure what the question is trying to ask, surely the question
  is trivial?
I understand what a Cauchy sequence is but why does the question
  specify "real numbers"?
How does the proof answer the question?
Comment: Because $||x||$ is a real number.
Comment: Some times it may ask you to use $\epsilon$. :)
Comment: If $\{x_n \} $ is Cauchy seqence then for any $\varepsilon >0$ there exists $N$ such that $||x_k -x_j ||\leq \varepsilon $ for $k,j \geq N.$ Thus if you take any $\varepsilon >0$ then $$|||x_k || -||x_j |||\leq ||x_k - x_j ||\leq \varepsilon$$ for $k,j \geq N.$  hence $\{||x_n ||\} $ is Cauchy sequence.
Comment: @motylanogatomkamazura I understand that but why does the question specify real numbers?
Comment: Could the three of you please write $\|x\|$ instead of $||x||$?  I corrected this in the question itself.  Notice how conspicuous this looks in the following context: $||a|| ||b||$ versus $\|a\|\|b\|$ (as if it weren't already conspicuous before that). $\qquad$
Answer: The hypothesis that $\langle x_n:n\in\Bbb N\rangle$ is a Cauchy sequence in $X$ means that

for each $\epsilon>0$ there is an $m\in\Bbb N$ such that $\|x_k-x_\ell\|<\epsilon$ whenever $k,\ell\ge m$.

The desired conclusion, that $\langle\|x_n\|:n\in\Bbb N\rangle$ is a Cauchy sequence in $\Bbb R$, means that

for each $\epsilon>0$ there is an $m\in\Bbb N$ such that $\big|\|x_k\|-\|x_\ell\|\big|<\epsilon$ whenever $k,\ell\ge m$.

As you can see, these are not the same statement: the first is a statement about a sequence of vectors in $X$, and the second is a statement about the sequence of the norms of those vectors, which is a sequence of real numbers. Thus, there is definitely something to be proved.
To prove it, suppose that $\langle x_n:n\in\Bbb N\rangle$ is Cauchy in $X$, and let $\epsilon>0$ be arbitrary. By hypothesis there is an $m\in\Bbb N$ such that $\|x_k-x_\ell\|<\epsilon$ whenever $k,\ell\ge m$. Now use the fact, mentioned in your question, that
$$\|u\|-\|v\|\le\|u-v\|\tag{1}$$
for any $u,v\in X$: since $(1)$ holds for all $u$ and $v$, it's equally true that
$$-(\|u\|-\|v\|)=\|v\|-\|u\|\le\|v-u\|=\|u-v\|\;.\tag{2}$$
$(1)$ and $(2)$ together imply that
$$\big|\|u\|-\|v\|\big|\le\|u-v\|\;.$$
Now apply this to any $x_k$ and $x_\ell$ with $k,\ell\ge m$:
$$\big|\|x_k\|-\|x_\ell\|\big|\le\|x_k-x_\ell\|<\epsilon\;.$$
Thus, $\big|\|x_k\|-\|x_\ell\|\big|<\epsilon$ whenever $k,\ell\ge m$, and $\langle\|x_n\|:n\in\Bbb N\rangle$ is indeed a Cauchy sequence in $\Bbb R$.
Comment: How would it be different if it was a Cauchy sequence in $\mathbb{C}$?
Comment: @Aljabra: If what were a Cauchy sequence in $\Bbb C$?
Comment: if the question was the $x_n$ is a Cauchy sequence of complex numbers?
Comment: @Aljabra: No difference at all.
Answer: $$
\|u\| = \overbrace{\|(u-v)+v\| \le \|u-v\| + \|v\|}^\text{This is a basic property of norms.};
$$
therefore
$$
\|u\|-\|v\| \le \|u-v\|. \tag 1
$$
But the same reasoning can show that
$$
\|v\|-\|u\| \le \|v-u\|. \tag 2
$$
To say that $(1)$ and $(2)$ are both true is to say that
$$
\left| \|u\| - \|v\| \right| \le \|u-v\|.
$$
Consequently if you've shown that $\|u-v\| \le \varepsilon$, you can conclude that $\left| \|u\|-\|v\| \right| \le \varepsilon$.


How to calculate cutting angle for a circle of tiles?

Question: I'm looking to calculate the angle I need to cut on square tiles that will be arranged around the edge of a circular pool.
Given that radius is 7' and that tile width is 12", how many tiles are needed to close the full circle, when distance between each tile is 1/4". At what angle does each tile need to be cut on both sides, so that when laid in a circle, sides of the tiles are parallel to each other? Can somebody point me in how to calculate this?
Comment: Other than a different size, pretty most of the answer here applies: http://gardening.stackexchange.com/questions/14498/stone-degree-cut-for-fire-pit/14499#14499
Answer: Assuming you are just going to tile a simple circle with a radius of 7', the calculation is easy to estimate number of tiles.
<code>πR2 = Area
</code>
I'm going to use inches here: Radius is 84" = surface area of 22,156" squared.
It wouldn't be out of the question to calculate the number of tiles out of this, and add in a percentage for breakage/cuts. based on a 12" tile and 1/4" grout, I'd guess 150 tiles + 20% breakage/waste, or 177 tiles.
The next part gets more complicated. What I believe you're suggesting is cutting trapezoidal sections of tile, and arrange them in concentric rings. If you want to maximize the tile size, the pitch will be the same, but will not have the same layout on each and every tile. For each consecutive ring of tiles form the center, they will become more oblique and large.

I suggest doing an accurate scaled drawing in the spirit of what I threw together. Using autocad or sketchup would be highly advisable to make a 2D drawing. This is really the easiest way in my mind. Then you can have a firm plan of cuts, measurable angles, as well as a count of tiles.
Keep in mind, this is just about layout and measurements. I have NO idea of the tiles cut like this will be stable or if it will be easy to install.
Take your time, measure twice, cut once and when in doubt, step away and ask yourself "Is this work going to be worth the outcome".
Good luck and let us know how it goes!
Answer: For your circle & tiles:
12-1/4 inches if you leave the tile full-width at the outside edge - tile plus grout.
2 pi R is circumference - 43.923 feet. 527.79 inches.
Divide by 12.25 to get number of tiles. 43.084 - depending on the project, you either figure 43 is close enough (0.27 inch grout line rather than 0.25) or you use 44 tiles and trim more off them (not full width at edge - 11.745" at outer edge.)
360 degrees in a circle divided by number of tiles = the angle of cut
360 degrees divided by 43 = 8.37 degrees per tile, to make symmetric, cut 4.185 degrees on each side. For 44 tiles, 8.18, 4.09.
To get fussy (the 43/44 may be near enough to make it matter) you could check with the fact that the edge of the tile is not really "the circumference of the circle" but a chord making up a polygon inscribed in the circle. Chord length = 2 * r * sin (c/2) where c is the "central angle" - so c/2 is 4.185 or 4.09 degrees for 43 or 44 tiles, respectively. Looks like it might make it 0.26 rather than 0.27 inch grout line for 43.
In real life, start from opposite sides and work to the point where you have one tile left on each side - check the fit of that as constructed and trim to fit as needed, since getting grout lines precisely repeatable to the 100th of an inch is unlikely in practice.
Answer: I accepted answer but wanted to provide my line of thinking also, and some facts that were missing in initial question, and that is that length of the tile is 18" and that there will be a 1" overhand over the circle. Here is how I calculated it:
Circumference  of the circle is 43.98, let's round it up to 44. Since I want the tiles at the end not to be cut, and there will be overhand of 1", outer circle radius is 84 + 17 = 101. So outer circle circumference is 52.88', lets round it up to 53'. So basically inner circle is 9 feet shorter then outer one. Inner circle due to gap of 1/4" between tiles can hold only 43 tiles. So from these 43 tiles I have to take away 9'.
9x12 = 108/43 = 2.51. So from each tile I have to take away 2.5 inches, so on each side that is 1.25". Now if we apply trigonometry, since we know all the pieces we can calculate the angle of the cut. Based on opposite and adjacent side length, angle on the top of the tile is 3.97 degrees. I think that is pretty close to what others came up with. It is not absolutely necessary that it fits exactly as the circle will not be closed, only half circle will be created. This is for the pool coping.


Python ast package: traversing object hierarchies

Question: The following is a Python code snippet using the ast and symtable
packages.  I am trying to parse the code and check the types.  But I
don't understand how to traverse objects to get to the actual variable
being referenced.
The following code implements a NodeVisitor, and a function is presented to the compiler and parsed by the compiler and the ast walked.  The function being analyzed (eval_types) is passed a couple objects.
Below are the code chunks that make up the example.  I have added some comments for each chunk.  To run the code, the "chunks" need to be reassembled.
The imports and a function to un-indent a block of code for parsing.
import inspect
import ast
import symtable
from tokenize import generate_tokens, untokenize, INDENT
from cStringIO import StringIO

# _dedent borrowed from the myhdl package (www.myhdl.org)
def _dedent(s):
    """Dedent python code string."""

    result = [t[:2] for t in generate_tokens(StringIO(s).readline)]
    # set initial indent to 0 if any
    if result[0][0] == INDENT:
        result[0] = (INDENT, '')
    return untokenize(result)

The following is the node visitor, it has the generic unhandled and name visitor overloads.
class NodeVisitor(ast.NodeVisitor):
    def __init__(self, SymbolTable):
        self.symtable = SymbolTable
        for child in SymbolTable.get_children():
            self.symtable = child
            print(child.get_symbols())

    def _visit_children(self, node):
        """Determine if the node has children and visit"""
        for _, value in ast.iter_fields(node):
            if isinstance(value, list):
                for item in value:
                    if isinstance(item, ast.AST):
                        print('  visit item %s' % (type(item).__name__))
                        self.visit(item)

            elif isinstance(value, ast.AST):
                print('  visit value %s' % (type(value).__name__))
                self.visit(value)

    def generic_visit(self, node):
        print(type(node).__name__)
        self._visit_children(node)

    def visit_Name(self, node):
        print('  variable %s type %s' % (node.id,
                                         self.symtable.lookup(node.id)))
        print(dir(self.symtable.lookup(node.id)))

The following are some simple classes that will be used in the function that will be parsed and analyzed with the AST.
class MyObj(object):
    def __init__(self):
        self.val = None

class MyObjFloat(object):
    def __init__(self):
        self.x = 1.

class MyObjInt(object):
    def __init__(self):
        self.x = 1

class MyObjObj(object):
    def __init__(self):
        self.xi = MyObjInt()
        self.xf = MyObjFloat()

The following is the test function, the eval_types function is the function that will be analyzed with the AST.
def testFunc(x,y,xo,z):

    def eval_types():
        z.val = x + y + xo.xi.x + xo.xf.x

    return eval_types

The code to execute the example, compile the function and analyze.
if __name__ == '__main__':
    z = MyObj()
    print(z.val)
    f = testFunc(1, 2, MyObjObj(), z)
    f()
    print(z.val)
    s = inspect.getsource(f)
    s = _dedent(s)
    print(type(s))
    print(s)

    SymbolTable = symtable.symtable(s,'string','exec')
    tree = ast.parse(s)
    v = NodeVisitor(SymbolTable)
    v.visit(tree)

The following is an example output up to the first name visit.
Module
  visit item FunctionDef
FunctionDef
  visit value arguments
arguments
  visit item Assign
Assign
  visit item Attribute
Attribute
  visit value Name
  variable z type <symbol 'z'>
['_Symbol__flags', '_Symbol__name', '_Symbol__namespaces',
 '_Symbol__scope', '__class__', '__delattr__', '__dict__',
 '__doc__', '__format__', '__getattribute__', '__hash__',
 '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__',
 '__repr__', '__setattr__', '__sizeof__', '__str__',
 '__subclasshook__', '__weakref__', 'get_name', 'get_namespace',
 'get_namespaces', 'is_assigned', 'is_declared_global',
 'is_free', 'is_global', 'is_imported', 'is_local',
 'is_namespace', 'is_parameter', 'is_referenced']

Creating the node visitor doesn't seem to bad but I can't figure out
how to traverse an object hierarchy.  In the general case the variable
being accessed could be buried deep in a object.  How to get to the actual variable being accessed from the ast visitor?  I only see that an object is at the node but no additional information what the result variable access is.
Comment: not sure i follow what you want.  is it that you can't find ".val"?  have you tried recursing below that node?  it's a long time since i used this, but i seem to remember that you would need, in your case, to call visit_children from visit_name.
Comment: @andrewcooke Thanks for the comments!  Yes, I want to continue parsing the objects (z.val, xo.xi.x, xo.xf.x) and determine more information on the actual variable used in the statement.  The simple case would be, z = x + y + xo_xi_x + xo_xf_x, where the variables are not embedded (buried) in objects and the properties/attributes/type of the variable could be determined in the above code snippet.  I will experiment with calling visit_children explicitly on these types of nodes.  Thanks again.
Comment: Making small (slow) progress developing an understanding of the AST package.  For this example, the object "attributes" will travel down the **visit_Attribute**.  Now I simply need to determine when **visit_Name** has an object (has children?) then finish in the visit_Attribute and work backwards (back up the tree).
Comment: good luck.  the docs are terrible/non-existent - you just need to read all the source you can... (but it's pretty cool code).
Answer: I don't know if you're still looking for this, but it looks like you just need to add a visit_Attribute and traverse backwards.  If you add this to your example:
def visit_Attribute(self, node):
    print('  attribute %s' % node.attr)
    self._visit_children(node)

Then the output for xo.xf.x is:
Add
  visit value Attribute
  attribute x
  visit value Attribute
  attribute xf
  visit value Name
  variable xo type <symbol 'xo'>
  visit value Load

Depending what you want to do with this, you would just need to store the attributes in a list until a Name is encountered, then reverse them.


unsigned char subtraction efficiency

Question: I have many files(about 50MB) which contains numbers between 0 and 255.
I Load them as unsigned char. What happens when I perform an subtraction between them? The results are always an integer(sizeof() gives 4) even when there are no overflows.
Comment: @Joachim: I think the question is the sentence with the question mark.
Answer: Formally they're promoted to int (on a usual machine where char is less than int) and then the arithmetic operation is performed.
In practice a compiler may notice that the result is converted back to char, and therefore emit only byte-size machine code.
Regarding the efficiency, if it is important then measure.
Comment: The importance of measuring cannot be stressed enough, since the efficiency will depend on the machine.  Most machines can't do arithmetic on bytes (which is why the language specifies implicit promotion).  Whether reading a byte into a register costs extra or not will depend on the architecture.  And if it does, the compiler may be able to optimize the cost out (as you describe for Intel), or not.

unsigned char subtraction efficiency