text:
Q: Do you have a Rails development environment running under Windows you're happy with? My current Rails development environment is Aptana + RadRails plugin on Windows XP and it's a little slow running tests, rake, and generators.
If you've evolved and proven your Windows Ruby on Rails development environment into something you're happy with and is fast, please share the details below.
Many thanks,
Eliot

A: http://www.akitaonrails.com/2009/1/13/the-best-environment-for-rails-on-windows
try this guide

A: Although I work primarily with Ubuntu now, I was using a windows machine with Vim on it. Vim has a plugin called rails.vim. It understands the rails structure very well. These the things I found very useful.

*

*Navigation between model, controller, unit test, functional test within 3-4 keystrokes using :RModel, RUnittest, :RFunctionaltest, RController.

*Ability to run a unit/functional/integration test right away using :Rake

*A quick jump to console using :RConsole

*A quick jump to helpers using :RHelper

*the goto file 'gf' shortcut now behaves in a predictable manner. It even looks up files inside gems you have installed.

The video on the site hardly does any justice to it. If you are not a vim user, then I would suggest E text editor. It is not free but worth every penny you pay.

A: To add on to Omar: instead of dealing with VMWare, you could install Portable Ubuntu, which runs inside Windows. Though you will get a performance hit from doing so, it will give you a Linux environment to work in and you won't have to worry about installing another operating system.

A: I am led to believe that Rails (well, Ruby, really) on Windows is generally slow, compared to *n[iu]x, but since I haven't experienced the latter, I remain blissfully ignorant. In particular, there's a lag while the Rails environment loads that is tedious even on a fairly fast (3GHz Xeon) box.
On top of that, there's the overhead that an IDE brings. Of the more recent, I've tried NetBeans and RubyMine. Both are very capable and a little slow, compared to my normal working environment of command line and test editor, which pretty much suffice 95% of the time: I find I don't need much IDE support when I'm developing test-first. I still find myself mostly using SciTE, largely because of the "Run" command being easily accessible. With a little tweak to the "require test_helper" line in my tests, a single test execution is no more than a F5 away, and the whole suite available from the command line with a quick "rake".
If I need to debug into the framework to clear up (usually) some misunderstanding on my part, then I currently lean towards NetBeans, where the debugger seems a little more intuitive. I suspect RubyMine may have more power, but I haven't found myself needing it yet.
Irrespective of all the above though, the key to performance on Windows is the time to execute `environment.rb' and that's not an easy nut to crack. (Here's hoping I'm totally wrong and I've missed something super-cool, btw.)

A: I would seriously consider against Rails development inside Windows and my reasoning behind it is because you won't be using a Windows machine in production.
You will most likely be running some sort of Linux machine because Passenger wont work on Windows, mongrel_cluster (last time I checked) also doesn't run on Windows and IIS is a nightmare. Trust me, consistency between development and production is a huge bonus.
If you must run Windows, then I would recommend running Rails inside a Virtual Machine with a Linux distribution of your choice. That way you could use something like e-texteditor (which comes highly recommended as a great alternative to Textmate) and have a Samba share to a git/svn repository on your Virtual Machine.
Check VMWare Server out and install CentOS / Ubuntu. It's free and will give you an insight into development in Linux which is ultimately where you want to be at.

A: I'd recommend jruby for windows.

A: If there are not immutable reasons that you are using Windows XP, you should just switch to Linux.  There are none of the weird compatibility issues that arise on Windows.  If your application will eventually be deployed to a linux machine, it's easier to develop on.  Plus, it would solve your performance issues.
https://help.ubuntu.com/community/RubyOnRails
If there are constrains that make Windows absolutely necessary, please revise and specify.

A: Ruby in Steel isn't bad if you want to use Visual Studio.
It's got it's issues, but it's not as "slow" as the eclipse variants I've tried.
RadRails so far has the most complete code completion I've seen, as it knows about your models and such far more than Ruby in Steel. Even if it's slow to load the data for it, at least it's there.


text:
Q: Building OPENCV For CARMA I got the following error when I run make
[ 27%] Built target pch_Generate_opencv_highgui
**Linking CXX shared library ../../lib/libopencv_highgui.so**
/usr/lib/gcc/arm-linux-gnueabi/4.5.3/../../../../arm-linux-gnueabi/bin/ld: cannot find -lgtk-x11-2.0
/usr/lib/gcc/arm-linux-gnueabi/4.5.3/../../../../arm-linux-gnueabi/bin/ld: cannot find -lgdk-x11-2.0
/usr/lib/gcc/arm-linux-gnueabi/4.5.3/../../../../arm-linux-gnueabi/bin/ld: cannot find -latk-1.0
/usr/lib/gcc/arm-linux-gnueabi/4.5.3/../../../../arm-linux-gnueabi/bin/ld: cannot find -lgio-2.0
/usr/lib/gcc/arm-linux-gnueabi/4.5.3/../../../../arm-linux-gnueabi/bin/ld: cannot find -lpangoft2-1.0
/usr/lib/gcc/arm-linux-gnueabi/4.5.3/../../../../arm-linux-gnueabi/bin/ld: cannot find -lpangocairo-1.0
/usr/lib/gcc/arm-linux-gnueabi/4.5.3/../../../../arm-linux-gnueabi/bin/ld: cannot find -lgdk_pixbuf-2.0

How can I solve this?

A: Your target system is missing GTK libs.
I don't know all missing libraries you reported, but you definitely need libgtk-2-dev along with it's dependencies.
You will also need Cairo and Pango libraries, but I don't know if they are included in GTK or not.
To get these libraries open you package manager and look for GTK 2.0, or do
apt-get -f install libgtk-2-dev from terminal. If you have aptitude of course.
Other option would be to install QT libraries and update OpenCV makfiles to link against QT.
EDIT:
I'm not Linux guru, so for directions how to install arbitrary libraries, you should refer to appropriate section of StackExchange (SuperUser, Linux, Ubuntu, ...).
Or in case you have some different platform to forums dedicated to that platform.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Real life examples of distributions with negative skewness Inspired by "real-life examples of common distributions", I wonder what pedagogical examples people use to demonstrate negative skewness? There are many "canonical" examples of symmetric or normal distributions used in teaching - even if ones like height and weight don't survive closer biological scrutiny! Blood pressure might be nearer normality. I like astronomical measurement errors - of historic interest, they are intuitively no more likely to lie in one direction than another, with small errors more likely than large.
Common pedagogical examples for positive skewness include people's incomes; mileage on used cars for sale; reaction times in a psychology experiment; house prices; number of accident claims by an insurance customer; number of children in a family. Their physical reasonableness often stems from being bounded below (usually by zero), with low values being plausible, even common, yet very large (sometimes orders of magnitude higher) values are well-known to occur.
For negative skew, I find it harder to give unambiguous and vivid examples that a younger audience (high schoolers) can intuitively grasp, perhaps because fewer real-life distributions have a clear upper bound. A bad-taste example I was taught at school was "number of fingers". Most folk have ten, but some lose one or more in accidents. The upshot was "99% of people have a higher-than-average number of fingers"! Polydactyly complicates the issue, as ten is not a strict upper bound; since both missing and extra fingers are rare events, it may be unclear to students which effect predominates.
I usually use a binomial distribution with high $p$. But students often find "number of satisfactory components in a batch is negatively skewed" less intuitive than the complementary fact  that "number of faulty components in a batch is positively skewed". (The textbook is industrially themed; I prefer cracked and intact eggs in a box of twelve.) Maybe students feel that "success" should be rare.
Another option is to point out that if $X$ is positively skewed then $-X$ is negatively skewed, but to place this in a practical context ("negative house prices are negatively skewed") seems doomed to pedagogical failure. While there are benefits to teaching the effects of data transformations, it seems wise to give a concrete example first. I would prefer one that does not seem artificial, where the negative skew is quite unambiguous, and for which students' life-experience should give them an awareness of the shape of the distribution.

A: In Stochastic Frontier Analysis, and specifically in its historically initial focus, production, the production function of a firm/production unit in general, is specified stochastically as
$$q = f(\mathbf x) + u-w$$
where $q$ is the actual output produced by the firm, and $f(\mathbf x)$ is its production function (which is understood more as an input-output relation rather than a mathematical expression reflecting "engineering" relations) with $\mathbf x$ being a vector of production inputs (capital, labor, energy, materials, etc). The production function in Economic Theory represents maximum output, given technology and inputs, i.e. it embodies full efficiency. Then $u$ is a zero-mean normal disturbance on the production process, and $w$ is a non-negative random variable representing deviation from full efficiency due to reasons that the econometrician may not know, but he can measure through this set up. This random variable is usually assume to follow a half-normal or exponential distribution. Assuming the half normal (for a reason), we have
$$u \sim N(0, \sigma_u^2),\;\; w\sim HN\left(\sqrt {\frac 2{\pi}}\sigma_2, \left(1- \frac 2{\pi}\right)\sigma_2^2\right)$$
where $\sigma_2$ is the standard deviation of the "underlying" normal random variable whose absolute value is the Half-normal.
The composite error-term $\varepsilon = u-w$ is characterized by the following density
$$f_{\varepsilon}(\varepsilon) = \frac 2{s_2}\phi\left(\varepsilon/s_2\right)\Phi\left((-\frac {\sigma_2}{\sigma_u})\cdot(\varepsilon/s_2)\right),\;\; s_2^2 = \sigma^2_u + \sigma^2_2$$
This is a skew-normal density, with location parameter $0$, scale parameter $s_2$ and skew parameter $(-\frac {\sigma_2}{\sigma_u})$, where $\phi$ and $\Phi$ are the standard normal pdf and cdf respectively. For $\sigma_u =1, \;\; \sigma_2 = 3$, the density looks like this:

So negative skewness is, I'd say,the most natural modelling of the efforts of human race itself: always deviating from its imagined ideal -in most cases lagging behind it (the negative part of the density), while in relatively fewer cases, transcending its perceived limits (the positive part of the density) . Students themselves can be modeled as such a production function. It is straightforward to map the symmetric disturbance and the one-sided error to aspects of real life. I cannot imagine how more intuitive can one get about it.

A: Asset price changes (returns) typically have negative skew - many small price increases with a few large price drops. The skew seems to hold for almost all types of assets: stocks prices, commodity prices, etc. The negative skew can be observed in monthly price changes but is much more evident when you start looking at daily or hourly price changes. I think this would be a good example because you can show the effects of frequency on skew.
More details: http://www.fusioninvesting.com/2010/09/what-is-skew-and-why-is-it-important/

A: Negative skewness is common in flood hydrology.  Below is an example of a flood frequency curve (South Creek at Mulgoa Rd, lat -33.8783, lon 150.7683) which I've taken from 'Australian Rainfall and Runoff' (ARR) the guide to flood estimation developed by Engineers, Australia.
There is a comment in ARR:

With negative skew, which is common with logarithmic values of floods
in Australia, the log Pearson III distribution has an upper bound.
This gives an upper limit to floods that can be drawn from the
distribution. In some cases this can cause problems in estimating
floods of low AEP, but often causes no problems in practice.
[Extracted from Australian Rainfall and Runoff - Volume 1, Book IV
Section 2.]

Often floods, at a particular location, are considered to have an upper bound called the 'Probable Maximum Flood' (PMF). There are standard ways of calculating a PMF.

A: Gestational age at delivery (especially for live births) is left skewed. Infants can be born alive very early (although chances of continued survival are small when too early), peak between 36-41 weeks, and drop fast. It is typical for women in the US to be induced if 41/42 weeks, so we don't usually see many deliveries after that point.

A: In fisheries there are often examples of negative skew because of regulatory requirements. For instance the length distribution of fish released in recreational fishery; because there is sometimes a minimum length that a fish must be in order for it to be retained all fish under the limit are discarded. But because people fish where there tends to be legal length fish there tends to be negative skew and mode towards the upper legal limit. The legal length does not represent a hard cut off though. Because of bag limits (or limits on the number of fish that can be brought back to the dock), people will still discard legal size fish when they have caught larger ones.
e.g., Sauls, B. 2012. A Summary of Data on the Size Distribution and Release Condition of Red Snapper Discards from Recreational Fishery Surveys in the Gulf of Mexico. SEDAR31-DW11. SEDAR, North Charleston, SC. 29 pp.

A: In the UK, price of a book. There is a "Recommended retail price" which will generally be the modal price, and virtually nowhere would you have to pay more. But some shops will discount, and a few will discount heavily.
Also, age at retirement. Most people retire at 65-68 which is when the state pension kicks in, very few people work longer, but some people retire in their 50s and quite a lot in their early 60s.
Then too, the number of GCSEs people get. Most kids are entered for 8-10 and so get 8-10. A small number do more. Some of the kids don't pass all their exams though, so there is a steady increase from 0 to 7.

A: Some great suggestions have been made on this thread. On the theme of age-related mortality, machine failure rates are frequently a function of machine age and would fall into this class of distributions. In addition to the financial factors already noted, financial loss functions and distributions typically resemble these shapes, particularly in the case of extreme-valued losses, e.g., as found in BIS III (Bank of International Settlement) estimates of expected shortfall (ES), or in BIS II the value at risk (VAR) as inputs to regulatory requirements for capital reserve allocations.

A: Nick Cox accurately commented that "age at death is negatively skewed in developed countries" which I thought was a great example.
I found the most convenient figures I could lay my hands on came from the Australian Bureau of Statistics (in particular, I used this Excel sheet), since their age bins went up to 100 year olds and the oldest Australian male was 111 , so I felt comfortable cutting off the final bin at 110 years. Other national statistical agencies often seemed to stop at 95 which made the final bin uncomfortably wide. The resulting histogram shows a very clear negative skew, as well as some other interesting features such as a small peak in death rate among young children, which would be well suited to class discussion and interpretation.

R code with raw data follows, the HistogramTools package proved very useful for plotting based on aggregated data! Thanks to this StackOverflow question for flagging it up.
library(HistogramTools)

deathCounts <- c(565, 116, 69, 78, 319, 501, 633, 655, 848, 1226, 1633, 2459, 3375, 4669, 6152, 7436, 9526, 12619, 12455, 7113, 2104, 241)
ageBreaks <- c(0, 1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 110)

myhist <- PreBinnedHistogram(
    breaks = ageBreaks,
    counts = deathCounts,
    xname = "Age at Death of Australian Males, 2012")
plot(myhist)

A: Age of retirement in the U.S. is negatively skewed. The majority of retirees are older with a few retiring relatively young.

A: In random matrix theory, the Tracy Widom distribution is right-skewed. This is the distribution of the largest eigenvalue of a random matrix. By symmetry, the smallest eigenvalue has negative Tracy Widom distribution, and is therefore left-skewed.
This is roughly due to the fact that random eigenvalues are akin to charged particles that repel each-other, and hence the largest eigenvalue tends to be pushed away from the rest. Here's an exaggerated picture (taken from here) :

A: Here are the results for the forty athletes who successfully completed a legal jump in the qualifying round of the 2012 Olympic men's long jump, presented in a kernel density plot with rug plot underneath.

It seems to be much easier to be a metre behind the main group of competitors than to be a metre ahead, which would explain the negative skewness.
I suspect some of the bunching at the top end is due to the athletes targeting qualification (which required a top twelve finish or a result of 8.10 metres or above) rather than achieving the longest possible distance. The fact that the top two results were 8.11 metres, just above the automatic qualifying mark, is strongly suggestive, as is the way the medal-winning jumps in the Final were both longer and more spread out at 8.31, 8.16 and 8.12 metres. Results in the Final had a slight, non-significant, negative skew.
For comparison, results for the Olympic Heptathlon at Seoul 1988 are available in the heptathlon data set in the R package HSAUR. In that competition there was no qualifying round but each event contributed points towards the final classification; the female competitors showed pronounced negative skewness in the high jump results and somewhat negative skew in the long jump. Interestingly this was not replicated in the throwing events (shot and javelin) even though they are also events in which a higher number corresponds to a better result. The final points scores were also somewhat negatively skewed.
Data and code
require(moments)
require(ggplot2)

sourceAddress <- "http://www.olympic.org/olympic-results/london-2012/athletics/long-jump-m"

longjump.df <- read.csv(header=TRUE, sep=",", text="
rank,name,country,distance
1,Mauro Vinicius DA SILVA,BRA,8.11
2,Marquise GOODWIN,USA,8.11
3,Aleksandr MENKOV,RUS,8.09
4,Greg RUTHERFORD,GBR,8.08
5,Christopher TOMLINSON,GBR,8.06
6,Michel TORNEUS,SWE,8.03
7,Godfrey Khotso MOKOENA,RSA,8.02
8,Will CLAYE,USA,7.99
9,Mitchell WATT,AUS,7.99,
10,Tyrone SMITH,BER,7.97,
11,Henry FRAYNE,AUS,7.95,
12,Sebastian BAYER,GER,7.92,
13,Christian REIF,GER,7.92,
14,Eusebio CACERES,ESP,7.92,
15,Aleksandr PETROV,RUS,7.89,
16,Sergey MORGUNOV,RUS,7.87,
17,Mohammad ARZANDEH,IRI,7.84,
18,Ignisious GAISAH,GHA,7.79,
19,Damar FORBES,JAM,7.79,
20,Jinzhe LI,CHN,7.77,
21,Raymond HIGGS,BAH,7.76,
22,Alyn CAMARA,GER,7.72,
23,Salim SDIRI,FRA,7.71,
24,Ndiss Kaba BADJI,SEN,7.66,
25,Arsen SARGSYAN,ARM,7.62,
26,Povilas MYKOLAITIS,LTU,7.61,
27,Stanley GBAGBEKE,NGR,7.59,
28,Marcos CHUVA,POR,7.55,
29,Louis TSATOUMAS,GRE,7.53,
30,Stepan WAGNER,CZE,7.50,
31,Viktor KUZNYETSOV,UKR,7.50,
32,Luis RIVERA,MEX,7.42,
33,Ching-Hsuan LIN,TPE,7.38,
33,Supanara SUKHASVASTI N A,THA,7.38,
35,Boleslav SKHIRTLADZE,GEO,7.26,
36,Xiaoyi ZHANG,CHN,7.25,
37,Mohamed Fathalla DIFALLAH,EGY,7.08,
38,Roman NOVOTNY,CZE,6.96,
39,George KITCHENS,USA,6.84,
40,Vardan PAHLEVANYAN,ARM,6.55,
NA,Luis MELIZ,ESP,NA,
NA,Irving SALADINO,PAN,NA")

roundedSkew <- signif(skewness(longjump.df$distance, na.rm=TRUE), 3)

ggplot(longjump.df, aes(x=distance)) +
    xlab("Distance in metres") +
    ggtitle("London 2012 Men's Long Jump qualifying round results") +
    geom_rug(size=0.8) +
    geom_density(fill="steelblue") +
    annotate("text", x=7.375, y=0.0625, colour="white", label=paste("Source:", sourceAddress), size=3) +
    annotate("rect", xmin = 6.25, xmax = 7.25, ymin = 0.5, ymax = 1.125, fill="white") +
    annotate("text", x=6.75, y=1, colour="black", label="Best jump in up to 3 attempts") +
    annotate("text", x=6.75, y=.875, colour="black", label="42 athletes competed") +
    annotate("text", x=6.75, y=.75, colour="black", label="2 athletes had no legal jump") +
    annotate("text", x=6.75, y=.625, colour="black", label=paste("Skewness = ", roundedSkew))

# Results of the top twelve who qualified for the Final were closer to symmetric
skewness(longjump.df$distance[1:12])
# -0.1248782

# Results in the Final (some had 3 jumps, others 6) were only slightly negatively skewed
skewness(c(8.31, 8.16, 8.12, 8.11, 8.10, 8.07, 8.01, 7.93, 7.85, 7.80, 7.78, 7.70))
# -0.08578357

# Compare to Seoul 1988 Heptathlon
require(HSAUR)
skewness(heptathlon)

A: Scores on easy tests, or alternatively, scores on tests for which students are especially motivated, tend to be left skew.
As a result, the SAT/ACT scores of students entering sought after colleges (and even more so, their GPAs) tend to be left skew. There's plenty of examples at collegeapps.about.com e.g. a plot of University of Chicago SAT/ACT and GPA is here.
Similarly GPAs of graduates are often left-skew, e.g. the histograms below of GPAs of white and black graduates at a for-profit university taken from Fig 5 of Gramling, Tim. "How five student characteristics accurately predict for-profit university graduation odds." SAGE Open 3.3 (2013): 2158244013497026.

(It's not hard to find other, similar examples.)


text:
Q: How to do forward URl Rewriting using ASP.NET website I want to know how to do forward URL rewriting in ASP.NET web applications. For example creating sub domain type of URL without creating Sub Domain at IIS .
For example if user types
http://subdomain.example.com

I would get this after doing my forward URL rewriting
http://www.example.com/name=subdomain

Is there any way to do this when I have an ASP.NET website?

A: Create one CS Class let say "MainClassName"
and write code as below in cs file
public class MainClassName
 {
   public static void SubClassName(RouteCollection routes)
       {
        routes.MapPageRoute(
         "RouteName",      // Route name
         "{name}-{some extentions}.aspx",      // Route URL (subdomain-example.aspx)
         "~/home.aspx",// Web page to handle route
        );
       }
  }

please write below code in globle.asmx page
void Application_Start(object sender, EventArgs e)
{
    MainClassName.SubClassName(RouteTable.Routes);
}

when you will use subdomain-example.aspx this url then, it will redirect to home.aspx?name=SubDomain

A: Create an ASP.NET web site and deploy it as subdomain.example.com
This site has one page, default.asp, which contains the single line <% Response.Redirect("www.example.com/name=subdomain") %>
Write another website and deploy it at www.example.com
It will work without complicated and error-prone URL rewriting logic


text:
Q: Radvd - prefix through RA With Radvd running on my router, my client PC as everyone says on net "automagically" gets an ipv6 address. Is there any way I can use the same prefix which is published by RADVD in its RA and make the same ubuntu client act as a router (by running RADVD) with this prefix on some other interface? If so, please explain the best way to do this.

A: The way for upstream network infrastructure to delegate whole prefixes to be used on the downstream side of downstream routers is not via router discovery (router advertisements and router solicitations) but via DHCP6-PD (Prefix Delegation).
But that requires a PD-capable DHCP server and router, and a way for the DHCP server to communicate the route table updates to the other routers (so that the upstream routers learn that they need to send traffic for that prefix to the upstream port on that router).
As @heavyd mentioned, each "Ethernet LAN" gets a whole /64 minimum, so if all you got from your ISP was a single /64, you can't subdivide it across routers. If you have a more generous prefix (shorter prefix length than /64) then you can split it up. If you decide to manually subdivide your prefix and assign a chunk of it to the downstream side of your PC, don't forget to give your router a static route for that chunk, pointing it at the upstream IPv6 address of your PC.


text:
Q: Which stream should I choose to getting data from the database? I'd like to ask you about using "hot" Flow streams in the android app.
Let's start with simple, example scenario. We have an app, with Room database, MVVM architecture pattern, and Flow with Coroutines for manipulating data from database.
There are a couple of fragments inside the app. Every fragment have it's own ViewModel, but they have one thing in common - all of them have same, two things from database:

*

*List with colors

*String with user favorite color.

I'd like to ask, if it is a good way to modify Flow from "cold" stream, to "hot", by using .stateIn. Since all of fragments have recalls to the List and String that I've meantioned above.
Does implementing the hot stream with LifeCycle.State.STARTED would be more efficient, than implementing the cold stream? I'm  just trying to figure out, which stream should I choose according to the situation.

A: Really, you almost always want to use a hot Flow on Android if you're not using Compose, because even if data is only used by one Fragment, that Fragment might get recreated during a screen rotation, and it would waste resources to restart the flow from scratch to fetch the same data every time the screen rotates.
(If you're using Compose, you likely want to disable screen rotation configuration changes in the manifest. But you still might like to use a hot flow for cases like when a user accidentally taps something to go to another screen and then backs up to the original fragment quickly.)

Does implementing the hot stream with LifeCycle.State.STARTED would be more efficient, than implementing the cold stream?

I don't know what you mean by implementing a hot stream with a Lifecycle state.
The common pattern for creating a hot Flow on Android is to use SharingStarted.WhileSubscribed(5000L). This allows the Flow to remain idle when not in use, but avoids restarting it during a screen rotation (which is assumed to take less than 5 seconds). You can probably reduce this number, but I think it's the same window of time Jetpack's LiveData uses.
Since you have separate ViewModels, but both Fragments want to use the same data, I think it makes sense to use shareIn or stateIn for a property in the shared repository class. This is probably breaking some MVVM "rule" since it's making your repository slightly aware of how your UI is designed. Up to you. The alternative I guess is to do it in a third ViewModel that is used by both of your Fragments.


text:
Q: CKQuery Comparing Dates returns empty array I am attempting to query a CloudKit private database by comparing two date fields.
 let predicate = NSPredicate(format: "timeStamp == %@", parcoursTimeStamp as CVarArg)
            let query = CKQuery(recordType: "ParcoursRecord", predicate: predicate)
            privateDatabase.perform(query, inZoneWith: recordZone.zoneID, completionHandler: { (result, error) in
                if let error = error {
                    print("Error querying for record: \(error.localizedDescription)")
                } else {
                    print("Query result: \(result)")
                }

        })

I only receive Query result: Optional([ ]) but never any results although I know the timeStamps I am comparing are the same. What am I doing wrong? Is the predicate defined incorrectly (which would be me guess)?

A: Supposing that you timestamp CKRecord type has been defined as NSDate...
let predicate = NSPredicate(format: "timeStamp ==  %@", parcoursTimeStamp  as NSDate)


text:
Q: Excel VBE inconsistent exports I am exporting .bas files from an .xls file as outlined here: Exporting A VBComponent Code Module To A Text File to check them in into an SVN repo.
I am encountering the following issue which causes a change in casing of variable names in the files that is actually not real (or at least not relevant).
Statements like these get reformatted/recased:
rngTenors.Cells(i, 1)
changes into
rngTenors.cells(i, 1)

(subtle but still different and it gets picked up by the diff tool that I use and hides the real changes on the file in the noise that this generates)
Any idea of ways to prevent this from happening would be appreciated.

A: I'm doing something similar but haven't seen what you are experiencing. I'm not using the same export routines but they look similar at first glance.
A couple of questions.

1) Are you using option explicit, and
  do you have a variable named cell
  anywhere?
2) If you Commit, then make a few changes, export the .bas file and Commit again, what does the diff look like?
3) Are you opening and diffing the .bas files in a code aware editor (eg: Ultraedit) that may be changing your capitalisation?

I'm just guessing... but VB editor capitalisation can be weird if you name variables the same as methods or properties. Also i don't see why your export would inconsistently export .Cell i'm guessing if it exports to .cell then it should always export to .cell and not be a problem.
These are just some ideas, good luck :)

A: The VBE keeps an internal cache of variable names, including the casing, so even though you found a variable called cell, and renamed it to be something else, VBA still thinks it is a valid name, and so it is preserving the casing across all usages of that text.
You can trick the VBE into resetting the variable casing (and this also works for casing problems on methods too) by temporarily declaring a variable with the correct casing:
Public Cell as String

And then deleting that variable. You should then find that all of the casings are fixed throughout your project (and any project that refers to it).

A: Indeed I found something in the code as was suggested above.
dim cell

I have now renamed this variable and no reformats have occurred since. I expect and hope that this has resolved the issue. Many thanks for help!


text:
Q: Find unsubcribed subcriptions id from Exchange Web services I am using Exchange web services (Exchange server 2010) to synchronize user's outlook calendar with my application.I implemented EWS Push Notifications to call back my application whenever events are created ,modified ,deleted by out look users. I achieved this by subscribing user's email credentials  with EWS.
Client application should send OK responses to server whenever it get callbacks from the server .If there are no OK responses from client application for some time the particular subscription will be automatically unsubscribed.
If client is unreachable for some time due to any unexpected reason i need to subscribe only unsubscribed users instead of subscribing all the users.
My issue now is how to get unsubscribed users/Or subscriptions Id's  from EWS?I couldn't find anything helpful regarding this in MSDN documentation.
Any one knows?
MSDN Reference
enter link description here

A: I believe the only way to do this is to make use of the StatusEvent
 (I call it the heartbeat).  When you subscribe, you set a parameter to indicate how often EWS is to POST to your Push HTTP listener.  (I use 3 minutes--YMMV.)  So after 3 minutes (plus a little extra to be sure), if you don't hear from EWS, either by a StatusEvent or some other "real" event for a subscription, then you should re-subscribe for that user.


text:
Q: orderBy and sort is not applied on the full dataframe The final result is sorted on column 'timestamp'. I have two scripts which only differ in one value provided to the column 'record_status' ('old' vs. 'older'). As data is sorted on column 'timestamp', the resulting order should be identic. However, the order is different. It looks like, in the first case, the sort is performed before the union, while it's placed after it.
Using orderBy instead of sort doesn't make any difference.
Why is it happening and how to prevent it? (I use Spark 3.0.2)
Script1 (full) - result after 4 runs (builds):

from transforms.api import transform, Output, incremental
from pyspark.sql import functions as F, types as T

@incremental(
    require_incremental=True,
)
@transform(
    out=Output("ri.foundry.main.dataset.a82be5aa-81f7-45cf-8c59-05912c8ed6c7"),
)
def compute(out, ctx):

    out_schema = T.StructType([
        T.StructField('c1', T.StringType()),
        T.StructField('timestamp', T.TimestampType()),
        T.StructField('record_status', T.StringType()),
    ])
    df_out = (
        out.dataframe('previous', out_schema)
        .withColumn('record_status', F.lit('older'))
    )

    df_upd = (
        ctx.spark_session.createDataFrame([('1',)], ['c1'])
        .withColumn('timestamp', F.current_timestamp())
        .withColumn('record_status', F.lit('new'))
    )

    df = df_out.unionByName(df_upd)
    df = df.sort('timestamp', ascending=False)

    out.set_mode('replace')
    out.write_dataframe(df)

Script2 (full) - result after 4 runs (builds):

from transforms.api import transform, Output, incremental
from pyspark.sql import functions as F, types as T

@incremental(
    require_incremental=True,
)
@transform(
    out=Output("ri.foundry.main.dataset.caee8f7a-64b0-4837-b4f3-d5a6d5dedd85"),
)
def compute(out, ctx):

    out_schema = T.StructType([
        T.StructField('c1', T.StringType()),
        T.StructField('timestamp', T.TimestampType()),
        T.StructField('record_status', T.StringType()),
    ])
    df_out = (
        out.dataframe('previous', out_schema)
        .withColumn('record_status', F.lit('old'))
    )

    df_upd = (
        ctx.spark_session.createDataFrame([('1',)], ['c1'])
        .withColumn('timestamp', F.current_timestamp())
        .withColumn('record_status', F.lit('new'))
    )

    df = df_out.unionByName(df_upd)
    df = df.sort('timestamp', ascending=False)

    out.set_mode('replace')
    out.write_dataframe(df)

Query plans in both transformations show that sorting must be performed after the union (inspecting logical and physical plans I see no differences except for IDs and RIDs, but all the transformation steps are in the same place):

Observation:
Using the following profile the sort works well (query plans don't change):
@configure(["KUBERNETES_NO_EXECUTORS_SMALL"])

A: As it turns out, this behavior is not caused by @incremental. It can be observed in a regular transformation too:
from transforms.api import transform, Output
from pyspark.sql import functions as F

@transform(
    out=Output("ri.foundry.main.dataset.beea7dd2-8da3-4abf-9103-464ec646dc00"),
)
def compute(out, ctx):

    data = [("1", "2022-02-16T17:48:15.653Z", "older"),
            ("1", "2022-02-16T17:46:58.054Z", "older"),
            ("1", "2022-02-16T17:50:50.850Z", "new")]
    df_inp = (
        ctx.spark_session.createDataFrame(data, ["c1", "timestamp", "record_status"])
        .withColumn("timestamp", F.to_timestamp("timestamp"))
        .withColumn("record_status", F.lit("older"))
    )
    df_upd = (
        ctx.spark_session.createDataFrame([('1',)], ['c1'])
        .withColumn('timestamp', F.current_timestamp())
        .withColumn('record_status', F.lit('new'))
    )

    df = df_inp.unionByName(df_upd)
    df = df.sort(F.desc('timestamp'))

    out.write_dataframe(df)

When asking the question, I provided 2 scripts: one containing supposedly working sort, the other - failing sort. The reality is that both scripts don't work, just the "correct" one needed more runs to start showing incorrect sort order:

The reason lies in the partitioning of input dfs. Apparently, sort and groupBy performs the sort only in partitions (there are several of them). For some reason data is not moved to one executor or driver. Therefore, the resulting combined dataset does not have a unified sort order. This is why the usage of profile "KUBERNETES_NO_EXECUTORS_SMALL" yielded correct sort order (all operations were performed in one node - the driver).
The only solution I could find was using df.coalesce just before the df.sort() line:
df = df_out.unionByName(df_upd)
df = df.coalesce(1)
df = df.sort(F.desc('timestamp'))

Since Spark 3.2.0, df = df.repartition(1) will also work.


text:
Q: Python Selenium Webdriver: Repeating the same information in for loop I am trying to retrieve text from the website (https://www.doc.govt.nz/parks-and-recreation/places-to-go/otago/places/dunedin-area/?tab-id=50578). I am trying to extract information present on the website. Here is my code that is retrieving the text:
driver = webdriver.Chrome(driverLocation)
driver.get('https://www.doc.govt.nz/parks-and-recreation/places-to-go/otago/places/dunedin-area/?tab-id=50578')
driver.implicitly_wait(20)

for element in driver.find_elements_by_xpath('//div[@class="profile-detail"]'):

    desc = element.find_element_by_xpath('//div[@class="profile-detail-body"]').text
    info = element.find_element_by_xpath('//div[@class="profile-info"]').text

    print(desc)
    print(info)

The problem is that it always repeats the first entry of the information present on the page (i.e. Allans Beach Track information). When I tried to retrieve the information using two separate loops, it works fine. Could you please guide me where am I making the mistake?

A:
The idea is to understand the structure of the elements and then
  define your scripting strategy .
I believe you are trying to access each list item present in the list
  "class="profileRepeater" which has multiple entries of
  "class="profile-info" and "profile-detail-body".

driver = webdriver.Chrome(driverLocation)
driver.get('https://www.doc.govt.nz/parks-and-recreation/places-to-go/otago/places/dunedin-area/?tab-id=50578')
driver.implicitly_wait(20)

parentElement = driver.find_element_by_class_name('profileRepeater')

for listItemElement in parentElement.find_element_by_tag_name('li'):

    desc = listItemElement.find_element_by_class_name('profile-detail-body').text
    info = listItemElement.find_element_by_class_name('profile-info').text

    print(desc)
    print(info)

this should print all of the different values in search results list
  items

A: When using xpath to locate an element from another element you need to specify current context . before the second path
for element in driver.find_elements_by_xpath('//div[@class="profile-detail"]'):
    desc = element.find_element_by_xpath('.//div[@class="profile-detail-body"]').text
    info = element.find_element_by_xpath('.//div[@class="profile-info"]').text

You can use class_name instead without any conditions
for element in driver.find_elements_by_class_name('profile-detail'):
    desc = element.find_element_by_class_name('profile-detail-body').text
    info = element.find_element_by_class_name('profile-info').text


text:
Q: Saving an Object (Data persistence) I've created an object like this:
company1.name = 'banana'
company1.value = 40

I would like to save this object. How can I do that?

A: I think it's a pretty strong assumption to assume that the object is a class. What if it's not a class?  There's also the assumption that the object was not defined in the interpreter.  What if it was defined in the interpreter?  Also, what if the attributes were added dynamically? When some python objects have attributes added to their __dict__ after creation, pickle doesn't respect the addition of those attributes (i.e. it 'forgets' they were added -- because pickle serializes by reference to the object definition).
In all these cases, pickle and cPickle can fail you horribly.
If you are looking to save an object (arbitrarily created), where you have attributes (either added in the object definition, or afterward)… your best bet is to use dill, which can serialize almost anything in python.
We start with a class…
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> class Company:
...     pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> with open('company.pkl', 'wb') as f:
...     pickle.dump(company1, f, pickle.HIGHEST_PROTOCOL)
...
>>>

Now shut down, and restart...
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('company.pkl', 'rb') as f:
...     company1 = pickle.load(f)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1090, in load_global
    klass = self.find_class(module, name)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1126, in find_class
    klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Company'
>>>

Oops… pickle can't handle it.  Let's try dill.  We'll throw in another object type (a lambda) for good measure.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
...     pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>>
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>>
>>> with open('company_dill.pkl', 'wb') as f:
...     dill.dump(company1, f)
...     dill.dump(company2, f)
...
>>>

And now read the file.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('company_dill.pkl', 'rb') as f:
...     company1 = dill.load(f)
...     company2 = dill.load(f)
...
>>> company1
<__main__.Company instance at 0x107909128>
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>>

It works. The reason pickle fails, and dill doesn't, is that dill treats __main__ like a module (for the most part), and also can pickle class definitions instead of pickling by reference (like pickle does).  The reason dill can pickle a lambda is that it gives it a name… then pickling magic can happen.
Actually, there's an easier way to save all these objects, especially if you have a lot of objects you've created.  Just dump the whole python session, and come back to it later.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
...     pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>>
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>>
>>> dill.dump_session('dill.pkl')
>>>

Now shut down your computer, go enjoy an espresso or whatever, and come back later...
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> dill.load_session('dill.pkl')
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>> company2
<function <lambda> at 0x1065f2938>

The only major drawback is that dill is not part of the python standard library. So if you can't install a python package on your server, then you can't use it.
However, if you are able to install python packages on your system, you can get the latest dill with git+https://github.com/uqfoundation/dill.git@master#egg=dill. And you can get the latest released version with pip install dill.

A: You could use the pickle module in the standard library.
Here's an elementary application of it to your example:
import pickle

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

with open('company_data.pkl', 'wb') as outp:
    company1 = Company('banana', 40)
    pickle.dump(company1, outp, pickle.HIGHEST_PROTOCOL)

    company2 = Company('spam', 42)
    pickle.dump(company2, outp, pickle.HIGHEST_PROTOCOL)

del company1
del company2

with open('company_data.pkl', 'rb') as inp:
    company1 = pickle.load(inp)
    print(company1.name)  # -> banana
    print(company1.value)  # -> 40

    company2 = pickle.load(inp)
    print(company2.name) # -> spam
    print(company2.value)  # -> 42

You could also define your own simple utility like the following which opens a file and writes a single object to it:
def save_object(obj, filename):
    with open(filename, 'wb') as outp:  # Overwrites any existing file.
        pickle.dump(obj, outp, pickle.HIGHEST_PROTOCOL)

# sample usage
save_object(company1, 'company1.pkl')

Update
Since this is such a popular answer, I'd like touch on a few slightly advanced usage topics.
cPickle (or _pickle) vs pickle
It's almost always preferable to actually use the cPickle module rather than pickle because the former is written in C and is much faster. There are some subtle differences between them, but in most situations they're equivalent and the C version will provide greatly superior performance. Switching to it couldn't be easier, just change the import statement to this:
import cPickle as pickle

In Python 3, cPickle was renamed _pickle, but doing this is no longer necessary since the pickle module now does it automatically—see What difference between pickle and _pickle in python 3?.
The rundown is you could use something like the following to ensure that your code will always use the C version when it's available in both Python 2 and 3:
try:
    import cPickle as pickle
except ModuleNotFoundError:
    import pickle

Data stream formats (protocols)
pickle can read and write files in several different, Python-specific, formats, called protocols as described in the documentation, "Protocol version 0" is ASCII and therefore "human-readable". Versions > 0 are binary and the highest one available depends on what version of Python is being used. The default also depends on Python version. In Python 2 the default was Protocol version 0, but in Python 3.8.1, it's Protocol version 4. In Python 3.x the module had a pickle.DEFAULT_PROTOCOL added to it, but that doesn't exist in Python 2.
Fortunately there's shorthand for writing pickle.HIGHEST_PROTOCOL in every call (assuming that's what you want, and you usually do), just use the literal number -1 — similar to referencing the last element of a sequence via a negative index.
So, instead of writing:
pickle.dump(obj, outp, pickle.HIGHEST_PROTOCOL)

You can just write:
pickle.dump(obj, outp, -1)

Either way, you'd only have specify the protocol once if you created a Pickler object for use in multiple pickle operations:
pickler = pickle.Pickler(outp, -1)
pickler.dump(obj1)
pickler.dump(obj2)
   etc...

Note: If you're in an environment running different versions of Python, then you'll probably want to explicitly use (i.e. hardcode) a specific protocol number that all of them can read (later versions can generally read files produced by earlier ones).
Multiple Objects
While a pickle file can contain any number of pickled objects, as shown in the above samples, when there's an unknown number of them, it's often easier to store them all in some sort of variably-sized container, like a list, tuple, or dict and write them all to the file in a single call:
tech_companies = [
    Company('Apple', 114.18), Company('Google', 908.60), Company('Microsoft', 69.18)
]
save_object(tech_companies, 'tech_companies.pkl')

and restore the list and everything in it later with:
with open('tech_companies.pkl', 'rb') as inp:
    tech_companies = pickle.load(inp)

The major advantage is you don't need to know how many object instances are saved in order to load them back later (although doing so without that information is possible, it requires some slightly specialized code). See the answers to the related question Saving and loading multiple objects in pickle file? for details on different ways to do this. Personally I liked @Lutz Prechelt's answer the best, so that's the approach used in the sample code below:
class Company:
    def __init__(self, name, value):
        self.name = name
        self.value = value

def pickle_loader(filename):
    """ Deserialize a file of pickled objects. """
    with open(filename, "rb") as f:
        while True:
            try:
                yield pickle.load(f)
            except EOFError:
                break

print('Companies in pickle file:')
for company in pickle_loader('company_data.pkl'):
    print('  name: {}, value: {}'.format(company.name, company.value))

A: You can use anycache to do the job for you. It considers all the details:

*

*It uses dill as backend,
which extends the python pickle module to handle lambda and all the nice
python features.

*It stores different objects to different files and reloads them properly.

*Limits cache size

*Allows cache clearing

*Allows sharing of objects between multiple runs

*Allows respect of input files which influence the result

Assuming you have a function myfunc which creates the instance:
from anycache import anycache

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

@anycache(cachedir='/path/to/your/cache')
def myfunc(name, value)
    return Company(name, value)

Anycache calls myfunc at the first time and pickles the result to a
file in cachedir using an unique identifier (depending on the function name and its arguments) as filename.
On any consecutive run, the pickled object is loaded.
If the cachedir is preserved between python runs, the pickled object is taken from the previous python run.
For any further details see the documentation

A: Newer versions of pandas has also a functionality to save pickles.
I find it easier. e.g.
pd.to_pickle(object_to_save,'/temp/saved_pkl.pickle' )

A: Quick example using company1 from your question, with python3.
import pickle

# Save the file
pickle.dump(company1, file = open("company1.pickle", "wb"))

# Reload the file
company1_reloaded = pickle.load(open("company1.pickle", "rb"))

However, as this answer noted, pickle often fails. So you should really use dill.
import dill

# Save the file
dill.dump(company1, file = open("company1.pickle", "wb"))

# Reload the file
company1_reloaded = dill.load(open("company1.pickle", "rb"))

A: While pickle is the most widely used option for serialising objects, it's not without its concerns, especially regarding security. It's possible to construct a Python object that, when deserialised, will execute arbitrary code. An example is included below.
import pickle

class Example:
    def __reduce__(self):
        print("Serialised")
        return print, ("Deserialised",)

example = Example()

serialised = pickle.dumps(example) # prints "Serialised"
pickle.loads(serialised) # prints "Deserialised"

While the above example is perfectly harmless, it would be trivial to make it much, much nastier, for example by replacing print with exec or eval in the return value.
There isn't really a good solution to this, but people have mentioned the dill library as a possible alternative to pickle. There is, however, another alternative, marshal. It's a builtin serialisation library, but it has the drawback that it doesn't work on some kinds of object (though, unlike pickle, it can serialise CodeObjects, which is why it is internally used to serialise the aforementioned during compilation of CodeObjects into .pyc files). It's also much faster, being in C (code here), but hasn't been rigorously audited. However, no security vulnerabilities are known.
marshal is effectively a drop-in replacement for pickle. The loads, load, dumps and dump methods all do exactly the same thing.


text:
Q: Big O of Recursive Methods I'm having difficulty determining the big O of simple recursive methods. I can't wrap my head around what happens when a method is called multiple times.  I would be more specific about my areas of confusion, but at the moment I'm trying to answer some hw questions, and in lieu of not wanting to cheat, I ask that anyone responding to this post come up with a simple recursive method and provide a simple explanation of the big O of said method. (Preferably in Java... a language I'm learning.)
Thank you.

A: You can define the order recursively as well. For instance, let's say you have a function f. To calculate f(n) takes k steps. Now you want to calculate f(n+1). Lets say f(n+1) calls f(n) once, then f(n+1) takes k + some constant steps. Each invocation will take some constant steps extra, so this method is O(n).
Now look at another example. Lets say you implement fibonacci naively by adding the two previous results:
fib(n) = { return fib(n-1) + fib(n-2) }

Now lets say you can calculate fib(n-2) and fib(n-1) both in about k steps. To calculate fib(n) you need k+k = 2*k steps. Now lets say you want to calculate fib(n+1). So you need twice as much steps as for fib(n-1). So this seems to be O(2^N)
Admittedly, this is not very formal, but hopefully this way you can get a bit of a feel.

A: You might want to refer to the master theorem for finding the big O of recursive methods. Here is the wikipedia article: http://en.wikipedia.org/wiki/Master_theorem
You want to think of a recursive problem like a tree. Then, consider each level of the tree and the amount of work required. Problems will generally fall into 3 categories, root heavy (first iteration >> rest of tree), balanced (each level has equal amounts of work), leaf heavy (last iteration >> rest of tree).
Taking merge sort as an example:
define mergeSort(list toSort):
    if(length of toSort <= 1):
        return toSort
    list left = toSort from [0, length of toSort/2)
    list right = toSort from [length of toSort/2, length of toSort)
    merge(mergeSort(left), mergeSort(right))

You can see that each call of mergeSort in turn calls 2 more mergeSorts of 1/2 the original length. We know that the merge procedure will take time proportional to the number of values being merged.
The recurrence relationship is then T(n) = 2*T(n/2)+O(n). The two comes from the 2 calls and the n/2 is from each call having only half the number of elements. However, at each level there are the same number of elements n which need to be merged, so the constant work at each level is O(n).
We know the work is evenly distributed (O(n) each depth) and the tree is log_2(n) deep, so the big O of the recursive function is O(n*log(n)).


text:
Q: HTML class not responding to jQuery action after using js.erb to render page after AJAX call Rails app I am writing an app that has follow functionality and this is done with a AJAX call to the controller. After that call I render the opposite button of the one that was clicked using js.erb that renders the button I want to show. However, I have a hover functionality on my button that after I click this button, the hover no longer works. It is the right class of button but the jQuery I use to change the state of the button does not work.
Here is some code, my jQuery:
unfollow_button = $(".unfollow-button");
unfollow_button.hover(
    function(){
        $(this).addClass("btn-danger");
        $(this).text("Unfollow");
    },
    function () {
        $(this).removeClass("btn-danger");
        $(this).text("Following");
    }
);

This is my view:
<% if current_user.following?(f) %>
<%= link_to "Following", user_unfollow_teacher_path(f), :class => "btn unfollow-button", :remote => true %>
<% else %>
<%= link_to "Follow", user_follow_teacher_path(f), :class => "btn btn-primary purple-button", :remote => true %>
<% end %>

And this is the js.erb file I use:
$("#follow_form").html("<%= escape_javascript(render('users/follow')) %>")

And this the partial that get rendered is:
<%= link_to "Following", user_unfollow_teacher_path(@user), :class => "unfollow-button btn", :remote => true %>

The jQuery works fine when I click unfollow, then after I follow again and have the button set to the unfollow-button the hover action stops working.
Any help would be appreciated thanks.

A: You will have to call that jquery code again in your js.erb file:
$("#follow_form").html("<%= escape_javascript(render('users/follow')) %>")
$(".unfollow-button").hover(
    function(){
        $(this).addClass("btn-danger");
        $(this).text("Unfollow");
    },
    function () {
        $(this).removeClass("btn-danger");
        $(this).text("Following");
    }
);

Its best not to have the code in multiple places, so I usually setup an initializer and that allows me to recall the same code in my .erb files (code below is in coffeescript, but you can convert it to js here
init.js.coffee
(myApp, $, undefined_) ->
  myApp.init = myApp.init or {}

  myApp.init.followHover = ->
    $(".unfollow-button").hover(#code here)

) window.myApp = window.myApp or {}, jQuery

$ ->
  myApp.init.followHover()

Then when you need it again in js.erb just call it!
$("#follow_form").html("<%= escape_javascript(render('users/follow')) %>")
myApp.init.followHover()

A: Delegate your javascript events like this. Now the JQUERY won't break after AJAX calls and this works beautifully with turbolinks turned on.
    $(function() {

      $("#follow_form").parent().delegate(".unfollow-button", "mouseover",
        function(){
          $(this).val("Unfollow");
          $(this).addClass("btn-danger");
        }
      );

      $("#follow_form").parent().delegate(".unfollow-button", "mouseout",
        function(){
          $(this).val("Following");
          $(this).removeClass("btn-danger");
        }
      );

    });

A: I think the problem is that the jQuery event listener isn't aware of the newly inserted DOM elements. Try using unfollow_button.on('hover', function()...
More info: http://api.jquery.com/on/


text:
Q: Question about Egorov's Theorem
Egorov's Theorem states that for a sequence of functions $f_n \to f$ pointwise on a subset $A \subset R$, $m(A)<\infty$, given $\epsilon>0$ there is a set $B \subset A$ such that $m(B)<\epsilon$ and $f_n \rightrightarrows f$ on $A-B$. Is it always true that given $\delta < \epsilon$ there is such a set $B_\delta$ such that $B_\delta \subset B_\epsilon$? If so, why? If not, what is a counterexample?

This is something I was thinking about today. My initial hunch (i.e. not at all formal) is that this statement is true; certainly it is for, say, $f_n(x)=x^n, f(x)=\chi_{\{1\}}$ on $[0,1]$. I have been trying to construct counterexamples in my head, but cannot. I think it underlies my lack of grasp about Egorov's Theorem - namely, why doesn't it say anything about the relationships between the sets $B_\epsilon$?


text:
Q: Why do some websites/applications require that passwords must begin with a letter? Some number of websites/applications require that a password must begin with a letter, I find this plain stupid. It's pretty annoying... and the password entropy (security) is greatly reduced.
So my question is... Is there a reason why some developers would choose this?
The only reasons I could think of are:

*

*They are sheep (Seen it required somewhere else and just copied the trend)

*Some just implement it because that's the little regex they know

*Just to create a false sense of security for their clients

(Asking because I'm developing an app to manage user passwords and thinking to alert the users that if the website asks for that, they should not trust their security)

A: Regarding security there is no reason such a password requirement makes sense, you already gave the answer yourself. I do not think that giving out a warning is necessary though, because the implementation is not necessarily an unsecure one.
In my opinion the only reasonable restriction for passwords is a minimum length. Other requirements can interfere with good password schemes and can actually reduce the strength of passwords, because users will switch to weaker passwords like "Password2014".


text:
Q: WP Google Suggest plug-in / JQuery submit on select The following code is from the WP Google Suggest plug-in
(function ($) {
    $.fn.googleSuggest = function (opts) {
        var services = {
            youtube: 'youtube',
            books: 'books',
            products: 'products',
            news: 'news',
            images: 'img',
            web: 'psy'
        };
        opts = $.extend({
            service: 'web',
            secure: false
        }, opts);
        opts.source = function (request, response) {
            $.ajax({
                url: 'http' + (opts.secure ? 's' : '') + '://suggestqueries.google.com/complete/search?callback=?',
                dataType: 'jsonp',
                data: {
                    q: request.term,
                    client: services['youtube'],
                    nolabels: 't'
                },
                success: function (data) {
                    response($.map(data[1], function (item) {
                        return {
                            value: $("<span>").html(item[0]).text()
                        }
                    }));
                }
            });
        };
        return this.each(function () {
            $(this).autocomplete(opts);
        });
    };
    $('#s').googleSuggest();
})(jQuery);

It is supposed to add a google suggest autocomplete search options in the Wordpress search field. The problem is that when you select the suggested search string, the form is just populated, but not submitted. You need to hit enter again in order to submit it. So, the question is how to add submit on select.
Thank you.
==============================================
Edit: I came back to this code and made some progress. I added the following code:
      opts.select = function(opts) {
      $(this).autocomplete(opts).parents('form').submit();
  }

before the "return" line;
    return this.each(function () {
..

Now, if I move up and down the auto-suggest results with the arrows, and hit enter, the form gets submitted with the correct string.
However, if the suggestion is clicked with a mouse, the original search string that was typed is submitted. An example of the behavior is as follows:
Search string entered in the form: one two
Automatic suggestions:
one two three
one two three four
one two three four five
When I click one of the automatic suggestions with the mouse, let's say "one two three four", it goes in the search field. The form gets submitted, but then it turns out that it was submitted with the original typed string "one two".
Thank you for any suggestions that you might have.
=======================================
I finally managed to solve the issue with an alternative code:
var suggestCallBack; // global var for autocomplete jsonp

jQuery(document).ready(function ($) {
    $("#s").autocomplete({
      select: function (event, ui) {
         var selectedObj = ui.item;
         $("#s").val(selectedObj.value);
         $('#cse-search-box').submit();
         },
        source: function(request, response) {
            $.getJSON("http://suggestqueries.google.com/complete/search?callback=?",
                {
                  "hl":"bg", // Language
                  "jsonp":"suggestCallBack", // jsonp callback function name
                  "q":request.term, // query term
                  "client":"youtube" // force youtube style response, i.e. jsonp
                }
            );
            suggestCallBack = function (data) {
                var suggestions = [];
                $.each(data[1], function(key, val) {
                    suggestions.push({"value":val[0]});
                });
                suggestions.length = 10; // prune suggestions list to only 5 items
                response(suggestions);

            };

        },
    });

});

The code was provided by the user PSR in a different question. It had to be modified a bit. The original code started with:
var suggestCallBack; // global var for autocomplete jsonp

$(document).ready(function () {

For Wordpress it had to start with:
var suggestCallBack; // global var for autocomplete jsonp

jQuery(document).ready(function ($) {

Case closed.


text:
Q: Retrieve post taxonomy inside get_posts() I am retrieving posts from my Custom Post Type using the built-in Wordpress get_posts() function.  I am able to print/retrieve all of the data for the post except the post's taxonomy term (which I registered as a custom taxonomy using register_taxonomy( 'developer_category', 'developer', $args ); Here's my code for displaying the posts...
<?php $devs = get_posts([
    'post_type'     => 'developer',
    'posts_per_page'    => '8',
    'orderby' => 'rand'
]); ?>

    <?php $post_count = 1; ?>
    <?php foreach ($devs as $dev): ?>
        <div class="loaded-dev" id="dev<?php echo $post_count; ?>">
            <?php echo get_the_post_thumbnail( $dev->ID, 'small' ); ?>
            <a href="<?php echo get_permalink($dev); ?>" class="full-link">

<?php echo $dev->post_title; ?>

<?php echo get_the_terms($dev->ID); ?> Developer

        <?php $post_count ++; ?>
    <?php endforeach; ?>

<?php wp_reset_postdata(); ?>

Using get_cat_name as I am above returns 'Uncategorized', I believe because it's looking for the default Wordpress category and I am categorizing by custom taxonomy.  How can I display my post's taxonomy name inside get_posts() ?

A: You need to pass the taxonomy to get_the_terms():
$my_tax_terms = get_the_terms( $dev->ID, 'developer_category' );

This returns an array of terms that you can then loop through. Also, you can't just echo it because it's an array. You can print_r( $my_tax_terms ) to see what you get, but you'll need to loop through the results to pull the information you want.


text:
Q: how does thread.interrupt() sets the flag? From the docs:
The Interrupt Status Flag
The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static isInterrupted method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.
By convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so. However, it's always possible that interrupt status will immediately be set again, by another thread invoking interrupt.
I read these SO posts. But I don't think I have understood this correctly. so I tested this on a sample code below.
I have two threads running in this. one is main and other Thread-0 which is labeled t.
I call t.interrupt() and I call Thread.currentThread().isInterrupted() in the run method.
Where exactly is the flag set?
Does Thread Class maintains a static list of all the Threads that is currently running and by calling Thread.currentThread() I get the currentThread Object and check if it is interrupted?
If the Thread class itself has the boolean flag interrupted, how does it differentiate between two threads; example main and Thread-0 here. Is the static flag same to both the Threads?
what exact sequences of steps are happening, set flag, where is the look up and unset flag etc?
when I uncomment the block of code below (which is currently commented out), the program never stops. I do not understand why?
import java.util.Random;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.TimeUnit;

    public class ThreadInterrupt {

        public static void main(String[] args) throws InterruptedException {

            System.out.println("Starting.");

            Thread t  = new Thread(new Runnable(){

                @Override
                public void run() {
                    Random ran = new Random();

                    for (int i = 0; i < 1E8; i++) {

                        /*try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            System.out.println("we have been interrupted");
                            e.printStackTrace();
                        }*/

                        if (Thread.currentThread().isInterrupted()) {
                            System.out.println("Interrupted!");
                            break;
                    }

                    Math.sin(ran.nextDouble());
        }
            }
        });
        t.start();

        Thread.sleep(500);
        t.interrupt();
        t.join();

        System.out.println("Finished.");
    }

}

A:
when I uncomment the block of code below (which is currently commented
  out), the program never stops. I do not understand why?

Note the javadoc of Thread#interrupt()

If this thread is blocked in an invocation of the wait(), wait(long),
  or wait(long, int) methods of the Object class, or of the join(),
  join(long), join(long, int), sleep(long), or sleep(long, int), methods
  of this class, then its interrupt status will be cleared and it will
  receive an InterruptedException.

So if you uncomment your code, the flag gets lifted and your if never executes.

Does Thread Class maintains a static list of all the Threads that is
  currently running and by calling Thread.currentThread()

The Thread.currentThread() method is declared as (Oracle JDK 7)
public static native Thread currentThread();

In other words, it is natively implemented, probably in C code. We can assume, given the javadoc, that, somewhere, a reference to all threads is stored. The currently executing one is returned.
Similarly, the Thread#isInterrupted() method calls
private native boolean isInterrupted(boolean ClearInterrupted);

which is also natively implemented. But we can assume it uses some boolean-style flag.

A:
Where exactly is the flag set?

The JVM Thread object keeps track of the flag.

Does Thread Class maintains a static list of all the Threads that is currently running and by calling Thread.currentThread() I get the currentThread Object and check if it is interrupted?

The Thread Class doesn't do it but the JVM does.  Thread.currentThread() is a static method which returns the Thread object that is associated with the calling thread.

If the Thread class itself has the boolean flag interrupted, how does it differentiate between two threads; example main and Thread-0 here

It is an instance field not a static field.  It is per Thread instance.

when I uncomment the block of code below (which is currently commented out), the program never stops. I do not understand why?

Because when you interrupt the thread, Thread.sleep(...) throws InterruptedException which clears the interrupt flag for the thread.  You always should re-interrupt the thread once you catch InterruptedException.
try {
     Thread.sleep(100);
} catch (InterruptedException e) {
     // _always_ reinterrupt the thread when you catch InterruptedException
     Thread.currentThread().interrupt();
     System.out.println("we have been interrupted");
     e.printStackTrace();
}


text:
Q: Get values from metatada.txt Is there a built in function in PyQGIS to import the values from a plugin's metadata.txt?
I am developing a plugin and want to show the version corresponding to the value from metadata.txt. Is there a native way to get the values or would I have to parse the file by myself?

A: No native way by my knowledge. Last time I used the fine code with a ConfigParser from Dockable MirrorMap plugin by Faunalia for an aboutbox.
import ConfigParser
import os
import platform

try:
    import resources
except ImportError:
    import resources_rc

class DlgAbout(QDialog, Ui_DlgAbout):

    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        config = ConfigParser.ConfigParser()
        config.read(os.path.join(os.path.dirname(__file__),'metadata.txt'))

        name        = config.get('general', 'name')
        description = config.get('general', 'description')
        version     = config.get('general', 'version')

        self.logo.setPixmap( QPixmap( ":/faunalia/logo" ) )
        self.title.setText( name )
        self.description.setText( description )

        text = self.txt.toHtml()
        text = text.replace( "$PLUGIN_NAME$", name )

        subject = "Help: %s" % name
        body = """\n\n
--------
Plugin name: %s
Plugin version: %s
Python version: %s
Platform: %s - %s
--------
""" % ( name, version, platform.python_version(), platform.system(), platform.version() )

        mail = QUrl( "mailto:abc@abc.com" )
        mail.addQueryItem( "subject", subject )
        mail.addQueryItem( "body", body )

        text = text.replace( "$MAIL_SUBJECT$", unicode(mail.encodedQueryItemValue( "subject" )) )
        text = text.replace( "$MAIL_BODY$", unicode(mail.encodedQueryItemValue( "body" )) )

        self.txt.setHtml(text)


text:
Q: VHDL - Shifting std_logic_vector by 8 bits Now that I have managed to shift my text while writing, I want to implement another feature, scrolling the text 1 digit per second. So for example I will will write "STACK" from keyboard, and then when I toggle a pin it will start floating on the seven segment display. I am getting multiple clocks error as I expected. Now, I got over that error with a counter but the text is not scrolling properly, random characters appear on random locations.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
use IEEE.numeric_std.all;

entity my_shifter is
        port(clk      : in  std_logic;
            doShift : in std_logic;--shift mode
            Scan_Dav : in  std_logic;--from keyboard module, new data
            Data_in  : in  std_logic_vector (7 downto 0);--scancode of the key pressed
            O1 : out std_logic_vector(7 downto 0);
            O2 : out std_logic_vector(7 downto 0);
            O3 : out std_logic_vector(7 downto 0);
            O4 : out std_logic_vector(7 downto 0)
            );
end my_shifter;

architecture bhv of my_shifter is

signal bytes : std_logic_vector(63 downto 0):=(others => '0');
signal Scan_Dav_Sync: std_logic_vector(1 downto 0):="00";
signal Previous_Scan_Dav: std_logic:='0';
signal shift : std_logic:='0';
signal flag : std_logic:='0';
signal first_letter: std_logic_vector(7 downto 0):="00000000";
begin
    process(clk)
        variable var:integer range 0 to 50000000 :=0;
        begin
            if rising_edge(clk) then
                if var = 50000000 then
                    var:=0;
                    flag<='0';
                    shift <= '1';
                else
                    flag <= '1';
                    var:=var+1;
                    shift <= '0';
                end if;
            end if;
    end process;

    process (clk, doShift)
        begin
            case doShift is

                when '0' =>
                    if rising_edge(clk) then
                        Scan_Dav_Sync(0) <= Scan_Dav;
                        Scan_Dav_Sync(1) <= Scan_Dav_Sync(0);
                        Previous_Scan_Dav <= Scan_Dav_Sync(1);
                        if (Previous_Scan_Dav = '0') and (Scan_Dav_Sync(1) = '1') then
                            bytes <= bytes (bytes'high-8 downto 0) & Data_in;
                        end if;
                    end if;--till here it works fine.

                when '1' => -- this is where it messes up
                    if (shift = '1' and flag = '0' ) then
                        first_letter <= bytes(bytes'high downto bytes'high-7);
                        bytes <= bytes (bytes'high-8 downto 0) & first_letter;
                    end if;

                when others =>--ignore here
                    bytes <= bytes (bytes'high-8 downto 0) & Data_in;

            end case;
    end process;
    O1 <= bytes(31 downto 24);
    O2 <= bytes(23 downto 16);
    O3 <= bytes(15 downto 8);
    O4 <= bytes(7 downto 0);
end bhv;

I wonder how I can overcome this issue? What or where is the error?

A: Most likely you can get away with this working if you make your second process a sane clocked process.
Something like:
process (clk)
begin
    if rising_edge(clk) then
        case doShift is
            when '0' =>
                Scan_Dav_Sync(0) <= Scan_Dav;
                Scan_Dav_Sync(1) <= Scan_Dav_Sync(0);
                Previous_Scan_Dav <= Scan_Dav_Sync(1);
                if (Previous_Scan_Dav = '0') and (Scan_Dav_Sync(1) = '1') then
                    bytes <= bytes (bytes'high-8 downto 0) & Data_in;
                end if;

            when '1' =>
                if (shift = '1' and flag = '0' ) then
                    first_letter <= bytes(bytes'high downto bytes'high-7);
                    bytes <= bytes (bytes'high-8 downto 0) & first_letter;
                end if;

            when others =>
                bytes <= bytes (bytes'high-8 downto 0) & Data_in;

        end case;
    end if;
end process;


text:
Q: How to fit the right mixed model? I want to look for a relashionship between the competition facing a hospital and mortality within the hospital. Assuming that patients in the same hospital may be more correlated than patients in different hospitals, I decided to adopt a mixed model.
I have a data set of more than 150k rows. The number of hospitals is 720
So I consider the hospital to be a random effect variable. I also consider Trimester (=20 modalities, because the study is 5 years of data divided into trimesters) as a random effect variable. The variables: Hospital_status (The status of the hospital) and Hospital_caseload(number of patients treated by the hospital) are related to the hospital and the other variables are related to the patients.
This is my model:
MultModel<-glmer(Death30~HHI+age+Sex++Emmergency+neoadjTrt+
                    denutrition+Charlson+Right colectomy+
                    colectomie_transverse+Total.colectomy+Hospital_status
                    Hospital_caseload+(1|Trimester)+(1|Hospital_ID),
                  data =data,family=binomial(link="logit"),nAGQ = 0)

However, I have some doubt about rightness of the model. What could be the problems if I don't take into account of hospital effect and fit the model below?
MultModel<-glmer(Death30~HHI+age+Sex++Emmergency+neoadjTrt+
                        denutrition+Charlson+Right colectomy+
                        colectomie_transverse+Total.colectomy+Hospital_status
                        Hospital_caseload+(1|Trimester),
                      data =data,family=binomial(link="logit"),nAGQ = 0)

But if take into account hospital effect, could it be a problem to put in the model the other variables related to hospital (that is Hospital_status and Hospital_caseload)
As a last question, does nAGQ=0 give a good model, I use it because of the slowness of R to run the model. What value should I give to nAGQ to have the most accurate and fastest model?What other tricks can I use to speed up the execution of the model without affecting the quality?

A:
What could be the problems if I don't take into account of hospital effect and fit the model below?

You have already answered that question yourself in your opening paragraph:

patients in the same hospital may be more correlated than patients in different hospitals

So, if you don't account for this, the standard errors for the fixed effets will be wrong. Random intercepts are a good way to do this. Alternatives are fitting fixd effects for hospitals, which is not a good idea here since you have so many, or generalised estimating equations (GEE) which can take even longer to fit that mixed models in some circumstances.

But if take into account hospital effect, could it be a problem to put in the model the other variables related to hospital (that is Hospital_status and Hospital_caseload)

There is nothing wrong with that. It is normal to include group level predictors.

As a last question, does nAGQ=0 give a good model, I use it because of the slowness of R to run the model. What value should I give to nAGQ to have the most accurate and fastest model?What other tricks can I use to speed up the execution of the model without affecting the quality?

You might get more accurate results with nAGQ>0. The higher the better. A good way to assess whether you need to is to take some samples from your dataset, run the models with nAGQ=0 and nAGQ>0 and compare the results on the smaller datasets. If you find little difference, then you have a good reason to stick with nAGQ=0 in the full dataset. For example you could randomly choose 72 hospitals and use all the observations from them. Alternatively you could just sample one tenth of the whole dataset. It would be good if you do this as many times as you can.
Apart from that, you can fit nAQG=0, extract the results from the fitted model, then refit the model with nAGQ>0 using the extracted results as the starting values. See this question and answer for details about why and how to do this:
Convergence in Linear Mixed-Effects Model
You could also try a different optimizer using lmercontrol. And finally you could running it on a faster machine and/or a machine with more memory. The cloud is a good and inexpensive way to do that.


text:
Q: javascript fires on load not click My goal:
Have an img in the defalt tab when the page loads. The user clicks on the img and it fades to revile the tab below.
My problem:
With in my html page I've placed a img tag. In the header there's a javascript that successfully fades the img when it's clicked. However when the img is placed with in the content section of "Tabs" area the fade fires when I load the page.  I'm sure there's a conflict between the two scripts. My fade script (on the html page) and the external javascript running the "Tabs".
A side note: I've done countless arrangements placing the img tag with in the html tag layout. As well working with the css.
thanks for any advice.
<!DOCTYPE HTML>

<meta charset="utf-8" />

<title>page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<link rel="stylesheet" href="CSS/style13.css" type="text/css" media="screen" />

<link rel=stylesheet type="text/css" href="tabstyle.css" />

`enter code here`

A: You placed the click on the entire document, not just images. You also fade all images, not just the clicked one.
$("img").click(function(){
   $(this).fadeOut('slow', function() {
       $(this).removeClass();
   });
});


text:
Q: How to call to a class object at the class itself? I'm new at Python and I'm trying to do something and hope you can help me:
If I'm defining a class at Python like: class foo:, and inside the class I want to do something with "foo" object, i.e. - I want that one of the objects of the class will be something like a=foo().
So, it should look like:
 class foo:
     def __init__(self):
         self.t=7

     a=foo() #it's outside init....

It is possible?
There is a way to do it?
(I'm trying to do this and it's always give me errors...)
(I tried to do import to the file but it doesn't help at all...)
Thank you!

A: Do it after the class definition:
class Foo:
    pass

Foo.a = Foo()

A: No. at the stage you define a = foo, foo is not defined. However, you can create a variable for foo instance inside foo like:
class Foo:
  def __init__(self):
    pass

  a = None

Foo.a = Foo()

edited according to the comments.


text:
Q: Finding Lifetime Incidence Based on Annual Incidence This question should be simple, but I can't wrap my head around it. The thing I can't wrap my head around most of all is how to calculate lifetime incidence among a whole population based on a certain amount per 1000 per year. Skip to the bold text if you want to give me a sufficient, hands-on explanation of this. I might even prefer an explanation of the bold text first so I can try the more complicated case-by-case situation myself.
There are about 21 million American males between the ages of 35 and 44. Approximately 3 per 1000 experience cardiovascular events each year (so 3 per 1000 per year).
Furthermore, there are about 22 million American males between the ages of 45-54. Their incidence rates of CVD lie at about 10 per 1000 per year.
There are about 17 million American males between the ages of 55-65, and the number of cardiovascular incidents is calculated to be about 21 per 1000 per year.
There are 18 million American males aged 65 and older. The incidence of their cardiovascular events lies at 65 per 1000 per year.
Given these numbers, what percentage of all American males will experience a cardiovascular event in their lifetime.
Say that there are 60 million American males between the ages of 35 and 65. Approximately 11 per 1000 experience cardiovascular events each year, i.e., 11 per 1000 per year. Assume this is the only category that experiences CVD-events. Given these numbers, what percentage of all American males will experience cardiovascular events in their lifetime assuming that there are 150 million American males?


text:
Q: c program loop in fork doesn't stop I am simulating F1 training. I am using fork() and shared memory between processes.

*

*I am generating a random time for the cars that need to run for 5,400,000.
I fork() for each car.
the sons must simulate the generation of times.
the father takes care of the display, he also makes a system ("clear") with a sleep (1) to slow down the display.

but the program does not stop despite the 5,400,000 limit.
The program lasts more than 20min without stopping!
I would like it to generate the display a number of times and stop!
Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <sys/wait.h>

#define NUMBER_OF_CARS 20
#define MIN 25000 // time generator
#define MAX 40000

int numeroVoiture[NUMBER_OF_CARS] = {44, 77, 11, 33, 3, 4, 5, 18, 14, 31, 16, 55, 10, 22, 7, 99, 9, 47, 6, 63};

typedef struct {

    unsigned int id;

    unsigned int s1;
    unsigned int s2;
    unsigned int s3;

    unsigned int best_S1;
    unsigned int best_S2;
    unsigned int best_S3;

    unsigned int tempsTotal;

    unsigned int best_Circuit;

    unsigned int lap;

    unsigned int compteurStand;

    unsigned int out;
} voiture;

voiture *shared_memory;
voiture copyTableau[NUMBER_OF_CARS];

int faireDesTours(int i);
unsigned int generateNumber(void);
void afficherTableau(void);
int compare (const void * a, const void * b);
void initVoiture(int i);
void sortLap(void);

int main(void)
{
    /***************************************************
    *           Creating shared memory        *
    ****************************************************/
    int segment_id = shmget(IPC_PRIVATE, sizeof(voiture) * NUMBER_OF_CARS, 0666 | IPC_CREAT);
    if (segment_id == -1) {
        perror("shmget() failed !");
        exit(EXIT_FAILURE);
    }

    shared_memory = shmat(segment_id, NULL, 0);
    if (shared_memory == (void *) (-1)) {
        perror("shmat() failed !");
        exit(EXIT_FAILURE);
    }

    /**********************************************************
     *               Creation of child / cars               *
     **********************************************************/
    for (int i = 0; i < NUMBER_OF_CARS; ++i)
    {
        /********  problem fork *********/
        pid_t pid = fork();
        if (pid == -1) {
            perror("fork failed !");
            exit(EXIT_FAILURE);
        }

        /********  child *********/
        if(pid == 0) {
            shared_memory[i].id = numeroVoiture[i]; //each car has a number
            faireDesTours(i); //5400000
        }

        /********  father  *********/
        else {
                wait(NULL);

                system("clear");

                // copy of array
                memcpy( copyTableau, shared_memory, sizeof(copyTableau) );

                //trier Tableau;
                qsort( copyTableau, NUMBER_OF_CARS, sizeof(voiture), compare );
                sortLap();

                afficherTableau();

                sleep(1);
        }

    }

    /********  Detach memory segments  *********/
    shmdt(shared_memory);

    /********  Delete shared memory  *********/
    shmctl(segment_id, IPC_RMID, NULL);

    exit(EXIT_SUCCESS);
}

unsigned int tempsMaxCircuit = 5400000;

int faireDesTours( int i ) {

    initVoiture(i);

    unsigned int tour_complet;

    while (shared_memory[i].tempsTotal <= tempsMaxCircuit) //no exceeded time
    {
        tour_complet = 0;

        srand(time(NULL) + getpid());

        /*   ****       S1     ****     */
        shared_memory[i].s1 = generateNumber();
        if (shared_memory[i].s1 < shared_memory[i].best_S1) {
            shared_memory[i].best_S1 = shared_memory[i].s1;
        }
        shared_memory[i].tempsTotal += shared_memory[i].s1;
        tour_complet += shared_memory[i].s1;
        /* *************************************** */

        if (shared_memory[i].tempsTotal >= tempsMaxCircuit)
        {
            break;
        }
        /*   ****       S2     ****     */
        shared_memory[i].s2 = generateNumber();
        if (shared_memory[i].s2 < shared_memory[i].best_S2) {
            shared_memory[i].best_S2 = shared_memory[i].s2;
        }
        shared_memory[i].tempsTotal += shared_memory[i].s2;
        tour_complet += shared_memory[i].s2;
        /* *************************************** */

        if (shared_memory[i].tempsTotal >= tempsMaxCircuit)
        {
            break;
        }

        /*   ****       S3     ****     */
        shared_memory[i].s3 = generateNumber();
        if (shared_memory[i].s3 < shared_memory[i].best_S3) {
            shared_memory[i].best_S3 = shared_memory[i].s3;
        }
        shared_memory[i].tempsTotal += shared_memory[i].s3;
        tour_complet += shared_memory[i].s3;
        /* *************************************** */

        /*   ****       Best Time Circuit     ****     */
        if (tour_complet < shared_memory[i].best_Circuit) {
            shared_memory[i].best_Circuit = tour_complet;
            shared_memory[i].best_Circuit = tour_complet;
        }
        /* *************************************** */
    }

    return 0;
}

unsigned int generateNumber(void)
{
    return rand()%(MAX-MIN+1)+MIN;
}

void afficherTableau(void) { // Display
    printf("\n\tBest times per complete lap\n");
    printf(" ===================================================================================\n");
    printf(" |     ID   |      s1     |      s2     |      s3     |     Tour     |     LAP     |\n");
    printf(" |==================================================================================\n");
    for (int i = 0; i < NUMBER_OF_CARS; i++){
        printf(" |     %2d   |    %5d    |    %5d    |    %5d    |    %6d    |    %5d    |\n", \
                copyTableau[i].id, \
                copyTableau[i].s1, copyTableau[i].s2, copyTableau[i].s3, \
                copyTableau[i].best_Circuit,\
                copyTableau[i].lap);
    }
    printf(" ===================================================================================\n\n");
}

// function sort
int compare(const void * a, const void * b)
{
    voiture *voitureA = (voiture *)a;
    voiture *voitureB = (voiture *)b;

    return ( voitureA->best_Circuit - voitureB->best_Circuit );
}

// init each structure value of car
void initVoiture(int i) {
    shared_memory[i].s1 = 0;
    shared_memory[i].s2 = 0;
    shared_memory[i].s3 = 0;

    shared_memory[i].best_S1 = MAX;
    shared_memory[i].best_S2 = MAX;
    shared_memory[i].best_S3 = MAX;

    shared_memory[i].best_Circuit = 3 * MAX;
    shared_memory[i].tempsTotal = 0;

    shared_memory[i].lap = 0;
    shared_memory[i].compteurStand = 0;
    shared_memory[i].out = false;
}

void sortLap(void) {

    unsigned int difference;

    for (int i = 1; i < NUMBER_OF_CARS; i++)
    {
        difference = ( copyTableau[i].best_Circuit - copyTableau[i - 1].best_Circuit );

        copyTableau[i].lap = difference;
    }
}

A: At the core, you have
    for (int i = 0; i < NUMBER_OF_CARS; ++i)
    {
        /********  problem fork *********/
        pid_t pid = fork();
        if (pid == -1) {
            perror("fork failed !");
            exit(EXIT_FAILURE);
        }

        /********  child *********/
        if(pid == 0) {
                ...
        }

        /********  father  *********/
        else {
                wait(NULL);
                ...
        }
    }

You're missing a call to exit in the child. Without this, each child loops around and starts creating children of its own. It will eventually end, but not after creating a huge number of processes unintentionally.
By the way, it's kind of weird to create a child if the first thing the parent does is wait for the child to end.


text:
Q: Getting error "TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'" for key in usersDict:
    user = usersDict.get(key)
    usersList.append(user)
    if user.get_Quantity() == 0:
        emptyStock = user.get_Name()
        flash("%s is out of stock!!")%emptyStock
    else:
        continue

Error message:

TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'

Is it wrong to use %s for a string?

A: Parenthesis is in the wrong place.

flash("%s is out of stock!!")%emptyStock

should be
flash("%s is out of stock!!"%emptyStock)


text:
Q: Getting values from multiple HTML elements I have a list of dates for events that customers can book via a form. At the moment, I have some cumbersome onclick script attached to  tags:

New York

20-24 January

This scrolls the page using the animatescroll jquery plugin, sets the date input on the form, sets the venue input on the form, and disables a checkbox. There are multiple dates for each venue so it adds a lot of code and is generally nasty.
I'd lack to package all this into a neat function, but how can I get the relevant venue and date text to use, bearing in mind the dates vary and there are multiple venues?

A: $('a').on('click', function (e) {
    $('#buy-form').animatescroll({scrollSpeed:700,easing:'easeInOutSine'});
    $('#date').val('20-24 January');
    $('#venue').val('New York');
    $('#resicheck').attr('disabled', true);
});

This is the case for one link. For multiple links you can attach a data element on every distinct element, for example:
20-24 January
22-25 January

And then use the following javascript
$('a').on('click', function (e) {
    $('#buy-form').animatescroll({scrollSpeed:700,easing:'easeInOutSine'});
    $('#date').val($(this).data('date'));
    $('#venue').val($(this).data('venue'));
    $('#resicheck').attr('disabled', true);
});

You can use jQuery (and javascript) to attach events and take out the code in html. Accessing an ID in jQuery is with #[id] and more information is on the jQuery site

A: Here's the script:
function updateDetails(loc, date) {
   $('#buy-form').animatescroll({scrollSpeed:700,easing:'easeInOutSine'});
   document.getElementById('date').value= date;
   document.getElementById('venue').value= loc;
   $('#resicheck').attr('disabled', true);
}

And, here's the mark-up:

New York

20-24 January
24-28 January

New Jersey

10-14 January


text:
Q: How to run php-fpm as root in docker When i run php-fpm in docker ,the default account is www-data ,but i want run as root in docker.
I edit the config file ,user and user group to root,but the I don't know how to add -R .so the container can't run.

A: If you check the default PHP-FPM container command, you will see that it uses the following default one: php-fpm. You can easily override it to php-fpm -R.
For docker-compose, I'm using the following config:
services:
  fpm:
    image: php:7.3-fpm
    volumes:
      - ./zzz-docker.conf:/usr/local/etc/php-fpm.d/zzz-docker.conf # Mount FPM config that runs FPM as root
    command: php-fpm -R # Allow running FPM as root

The config file is pretty simple:
; Config to run PHP FPM as root (requires the -R flag to be passed to the entrypoint)
[www]
user = root
group = root

Instead of mounting custom config and changing the command, you may build a custom image adding this config file to your Dockerfile and it will look like the following:
FROM php:7.3-fpm

COPY ./zzz-docker.conf /usr/local/etc/php-fpm.d/zzz-docker.conf

CMD ["php-fpm", "-R"]

The zzz-docker.conf file in these examples is located in the root directory of the project.
Remember that you should aware of the security risks of running PHP-FPM as root. I'm using the above config for development purposes only.

A: Here is how you can run bash as a root user:
First, find docker container id for php-fpm:
$ docker ps

p, 0.0.0.0:8008->80/tcp   webserver
e4689b3c1bc5        php:7.2-fpm                            "docker-php-entrypoi…"   2 months ago        Up 41 hours         9000/tcp

Then run the following command:
$ docker exec -u 0 -it e4689b3c1bc5 bash

Then you can run bash as a root user:
root@e4689b3c1bc5:/var/www#