text:
Q: Derivation of four-force We have two equivalent expressions for the four-momentum,
$$\textbf{P} = \gamma m (c,\vec{u}) \tag{1}\label{1}$$
$$\textbf{P} = (E/c,\vec{p}) \tag{2}\label{2}$$
where $\gamma = 1/\sqrt{1-(\frac{u}{c})^2}$. The four-force and the three-force are given by,
$$\textbf{F} = \frac{d \textbf{P}}{d\tau} \tag{3}\label{3}$$
$$\vec{f} = \frac{d \vec{p}}{dt} \tag{4}\label{4}$$
so that the four-force can be written as,
$$\textbf{F} = \frac{d}{d\tau}(E/c,\vec{p}) = \gamma \Big(\frac{dE}{cdt},\frac{d\vec{p}}{dt}\Big) = \gamma \Big(\frac{\vec{f} \cdot \vec{u}}{c},\vec{f}\Big)\tag{5}\label{5}.$$
There are several ways to derive,
$$\frac{dE}{dt} = \vec{f} \cdot \vec{u} \tag{6}\label{6}$$
to which I won't discuss the other ways on how to do it. I'm going to derive it the direct way, using the relativistic energy $E = \gamma mc^2$. So, $\frac{dE}{dt} = mc^2 \frac{d\gamma}{dt}$ (in this post I'm assuming a constant mass).
$$\frac{d\gamma}{dt} = \frac{\gamma^3}{c^2} u \frac{du}{dt} = \frac{\gamma^3}{c^2} \vec{u} \cdot \frac{d\vec{u}}{dt} \tag{7}\label{7}$$
$$\frac{dE}{dt} = \gamma^3 m \vec{u} \cdot \frac{d\vec{u}}{dt} \tag{8}\label{8}$$
The question now is how can we establish $\gamma^3 m \frac{d\vec{u}}{dt} = \vec{f}$? We need to have a form $\gamma^3 m \frac{d\vec{u}}{dt} = \frac{d(\gamma m\vec{u})}{dt} = \vec{f}$. So we study this form,
$$\frac{d(\gamma m\vec{u})}{dt} = \gamma m \frac{d\vec{u}}{dt} + m\vec{u} \frac{d\gamma}{dt} = \gamma m \frac{d\vec{u}}{dt} + \frac{\gamma^3 m}{c^2} \vec{u} \Big(\vec{u} \cdot \frac{d\vec{u}}{dt}\Big). \tag{9}\label{9}$$
Using vector algebra identity $A \times (B \times C) = (A \cdot C)B - (A \cdot B)C$, where $A=B=\vec{u}$ and $C=\frac{d\vec{u}}{dt}$,
$$\frac{d(\gamma m\vec{u})}{dt} = \gamma m \frac{d\vec{u}}{dt} + \frac{\gamma^3 m}{c^2} \vec{u} \Big(\vec{u} \cdot \frac{d\vec{u}}{dt}\Big) = \gamma m \frac{d\vec{u}}{dt} + \frac{\gamma^3 m}{c^2} \Bigg[(\vec{u} \cdot \vec{u}) \frac{d\vec{u}}{dt} + \vec{u} \times \Big(\vec{u} \times \frac{d\vec{u}}{dt}\Big)\Bigg]. \tag{10}\label{10}$$
If I assume $\vec{u} \times \frac{d\vec{u}}{dt} = 0$, then
$$\frac{d(\gamma m\vec{u})}{dt} = \gamma m \frac{d\vec{u}}{dt} + \frac{\gamma^3 m}{c^2} (\vec{u} \cdot \vec{u}) \frac{d\vec{u}}{dt} = \gamma m \frac{d\vec{u}}{dt} + \frac{\gamma^3 m}{c^2} u^2 \frac{d\vec{u}}{dt} = \gamma^3 m \frac{d\vec{u}}{dt}, \tag{11}\label{11}$$
the calculation of the equality in $\eqref{11}$ is plain algebra. Thus we have confirmed the form we needed in the statement above $\eqref{9}$. However, this can only be true if the three-force and velocity are completely aligned, but $\eqref{6}$ is a general form which does not say anything about the orientation of $\vec{f}$ and $\vec{u}$. Am I missing something here or is this really the case?

A: Your calculation is totally correct, but you have one small error in your argument. First of all, you correctly calculated that
$$\frac{\mathrm{d}E}{\mathrm{d}t}=mc^{2}\frac{\mathrm{d}\gamma}{\mathrm{d}t}=\gamma^{3}m\bigg (\vec{u}\cdot\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}\bigg ).$$
In the end you want to show that
$$\frac{\mathrm{d}E}{\mathrm{d}t}=\gamma^{3}m\bigg (\vec{u}\cdot\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}\bigg )\stackrel{!}{=}\vec{f}\cdot\vec{u}.$$
Now the error lies in the following step of yours: You said in order for the above equality to be true, we must have that
$$\gamma^{3}m\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}\stackrel{!}{=}\vec{f}$$
and this is what you tried to proof. However, this is not true. In general, if you have three vectors $\vec{a},\vec{b},\vec{c}\in\mathbb{R}^{3}$, then $\vec{a}\cdot\vec{c}=\vec{b}\cdot\vec{c}$ does in general NOT imply that $\vec{a}=\vec{b}$. You can easily construct counterexamples. Of course, if you would have that $\vec{f}=\gamma^{3}m\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}$ then the above claim is true, but again, the converse is in general not true, since you are not allowed to "cancel" in inner products.
To complete your proof, let us start again with the claim
$$\frac{\mathrm{d}E}{\mathrm{d}t}=\gamma^{3}m\bigg (\vec{u}\cdot\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}\bigg )\stackrel{!}{=}\vec{f}\cdot\vec{u}$$
In order to proof this, we just have to calculate the right-hand side, which is, following your correct formula (9), given by
$$\vec{f}\cdot\vec{u}=\frac{\mathrm{d}\vec{p}}{\mathrm{d}t}\cdot\vec{u}=\gamma m\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}\cdot\vec{u}=\bigg [\gamma m\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}+\frac{\gamma^{3}m}{c^{2}}\vec{u}\cdot\bigg (\vec{u}\cdot\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}\bigg )\bigg ]\cdot\vec{u}=...$$
As a next step, we can use your vector identity for the second term, so basically your step (10), but now with the difference that we have the addtional $\vec{u}$ on the right-hand side:
$$...=\gamma m\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}\cdot\vec{u}+\frac{\gamma^{3}m}{c^{2}}\bigg [(\vec{u}\cdot\vec{u})\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}+\vec{u}\times\bigg (\vec{u}\times\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}\bigg )\bigg ]\cdot\vec{u}$$
Now you see that the latter term always vanishes, since $\vec{u}\times\text{something}$ is perpendicular to $\vec{u}$ and hence
$$\underbrace{\bigg[\vec{u}\times\underbrace{\bigg (\vec{u}\times\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}\bigg )}_{\text{something}}\bigg ]}_{\perp\vec{u}}\cdot\vec{u}=0$$
But again, for this to work you need the  "$\cdot\vec{u}$" from the above formula $(\vec{f}\cdot\vec{u})$, since, as you said correctly, $\vec{u}$ is in general not parallel to $\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}$ and hence, $[\vec{u}\times(\vec{u}\times\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}) ]$ does in general not vanish.
Now you can proceed as in your equation (11), which shows that
$$\vec{f}\cdot\vec{u}=\gamma^{3}m\bigg (\frac{\mathrm{d}\vec{u}}{\mathrm{d}t}\cdot\vec{u}\bigg )$$
and hence proves your claim.


text:
Q: Register a task for another user logon I run a powershell script as Admiministrator, and I want to register a scheduled task for another user to run at logon.
The following powershell code will register an event for the Adiministrator user:
$action = New-ScheduledTaskAction -Execute 'C:\Windows\System32\notepad.exe'
$trigger = New-ScheduledTaskTrigger -AtLogOn
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "NotepadLaunch" -Description "Launch notepad at logon"

I see that the New-ScheduledTaskTrigger supports the -User option:
https://technet.microsoft.com/en-us/library/jj649821.aspx
User<String>

Specifies the identifier of the user for a trigger that starts a task when a user logs on.

Unfortunately the documentation is not very clear, and it doesn't seem to work as I would expect (setting the user where the action is triggered).
My question: is it possible to specify a different user when scheduling a task?
There are other suitable alternatives to set a command to be launched when another user logs on (assuming I'm using the Administrator user to set the command)?

A: Tested on Server 2012 and Powershell 3.0
$action = New-ScheduledTaskAction -Execute 'C:\Windows\System32\notepad.exe'
$trigger = New-ScheduledTaskTrigger -AtLogOn -User "DOMAIN\username"
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "NotepadLaunch" -Description "Launch notepad at logon" -User "DOMAIN\username"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bulk create a primary object and objects referencing the primary object at the same time? class Profile(models.Model):
    pass

class Experience(models.Model):
    profile = models.ForeignKey(Profile)

How would I save a a Profile along with a list of Experiences with a single transaction?
Right now I'm doing the following
p = Profile()
p.save()

e_list = [Experience(profile=p), Experience(profile=p)]
Education.objects.bulk_create(e_list)

Which is two database hits, can I do it in one?

A: Use transaction.atomic in order to have multiple queries in the same transaction:
from django.db import transaction

with transaction.atomic():
    p = Profile()
    p.save()

    e_list = [Experience(profile=p), Experience(profile=p)]
    Education.objects.bulk_create(e_list)


text:
Q: Closed subset of $L^1([0,1])$ I want to show this:

Consider $L^{1}([0,1])$ and $L^{2}([0,1])$, and
  $$G=\left\{ f \;\middle\vert\; \int_{0}^{1} |f|^2 \,dm \leq n \right\}\subseteq L^{2}([0,1]),$$  for some $n\in\mathbb{N}$. Show that $G$ is closed in $L^{1}([0,1])$ with the norm of $L^{1}([0,1])$. The measure being used here is Lebesgue measure.

I tried Minkowski and Hölder, but got nothing. Thanks for your help.

A: It's enough to show that $G$ is sequentially closed: let $(f_k,k\geqslant 1)$ be a sequence of elements of $G$, converging in $L^1$ to some $f$. Extracting a subsequence which converges almost everywhere, and using Fatou's lemma, we are done.


text:
Q: Accurate time-keeping in node.js I'm new to node.js, I'm trying to determine the elapsed time between an on and an off event of a switch (using BeagleBone Black), the script works, somewhat with .getTime() however from what I read it's not particularly accurate. So I did some research and attempted to use console.time, however from what I read there is no way to export the time value into a variable in this particular application.
I'm trying to write a script that times valve open and close events for an engine, so accuracy is paramount. The only input is a reed switch that is triggered by a passing magnet attached to a rotating flywheel.
More concisely, is there a way to time on/off events accurately in node.js?
var b = require('bonescript');

b.pinMode('P8_19', b.INPUT);
b.pinMode('P8_17', b.OUTPUT);
b.pinMode('USR3', b.OUTPUT);

b.attachInterrupt('P8_19', true, b.CHANGE, interruptCallback);

var cycle = 0;
//var t = 0;
var start, end;

function interruptCallback() {
     if (b.digitalRead('P8_19') == 1)
     {
    console.log('Magnetic field present!');
    cycle=cycle+1;
    console.log ('cycle: ' + cycle);
     }

    else
    {
    //console.time('t');
    start = (new Date()).getTime();
    }
    //console.timeEnd('t');
    //console.log(t);
    end = (new Date()).getTime();
    console.log('elapsed time: ' + (end - start));
}

This is the full code that I'm currently using. Note: I've also displayed how I attempted to use console.time.
Thank you for your help!

A: For the most accurate time measure possible, use process.hrtime(). From the documentation:

Returns the current high-resolution real time in a [seconds,
  nanoseconds] tuple Array. It is relative to an arbitrary time in the
  past. It is not related to the time of day and therefore not subject
  to clock drift. The primary use is for measuring performance between
  intervals.

The function returns a two-element array that contains the count of seconds and count of nanoseconds. Passing one time object into another will return the difference between the two objects.
For your case:
function interruptCallback() {
  if (b.digitalRead('P8_19') == 1) {
    cycle = cycle + 1;
  } else {
    start = process.hrtime();
  }
  end = process.hrtime(start);
  console.log('elapsed time: ' end[0] + ' seconds and ' + end[1] + 'nanoseonds.');
};


text:
Q: Qt add-in 1.2.4 visual studio 2013 bug enter image description herePC

*

*qt-opensource-windows-x86-msvc2013-5.5.1  and the 64bit version of it

*visual studio 2013 ultimate

*qt add-in 1.2.4

*windows 10 x64bit

problem:
when i create a qt project in vs and try to build it.
1- i get the error Qt5Widgetsd.lib(Qt5Widgetsd.dll) : fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'
note: the installed version of qt is the 64bit
2- the libraries and everything qt related isn't recognized in the IDE "uderlined red"
things i did to try and solve this problem
when i change the TARGET MACHINE to MachineX64 (/MACHINE:X64) instead of MachineX86 (/MACHINE:X86) (in project properties>linker>advanced) and the platform still as it was (win32)
vs recognize the qt things/libraries and the underlines goes, however when i build i get this error
Debug\moc_shitstackoverflow.obj : fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'x64'
when i change platform to x64
i get this error
the following error occurred: there's no qt version assigned to this project for platform x64. please use the "change QT version" feature and choose avalid qt version for this platform
and every thing get underlined again
so on an another failed attempt i uninstalled the 64bit of qt version and installed the 32bit one.
when i tried to build a newly created project in vs (under the 32bit) the project succeeded in building, however everything qt related was underlined red and the IDE don't recognizes it.
note* running vcvarsall.bat through qt cmd didn't change the underlining issue in vs in any of those cases!
so please i need help to this problem.
i tried everything i have found on the internet, but nothing solved the problem
so i wrote this very detailed explanation of what i have gone through the past 48 hours!
thanks in advance


text:
Q: How to Calculate Totals, Subtotals, and Average from Array in SwiftUI I'm new to SwiftUI and I've been stuck on this for a few days.
I have an unordered array that is identifiable.
I have a filter for that array in the parent view and the value of the filter gets passed down the child view.
I'm needing to group elements based on a value of one element in the array, then calculate the total, subtotals, and average based on another value set in each array element.
The calculation needs to update based on the filter being set to true or false in the parent view.
I solved this easily in JavaScript (React) by making the calculations inside the ForEach view but don't know how to solve this in SwitUI.
Any help at all is greatly appreciated!
struct Student: Identifiable {
    let id: String
    let name: String
    let gradeLevel: Int
    let studyHours: Int
}

class GetStudents: ObservableObject {

    @Published var items = [Student]()

    init() {
        self.items = [
            Student(id: "aa1", name: "Bobby", gradeLevel: 9, studyHours: 2),
            Student(id: "aa2", name: "Sally", gradeLevel: 12, studyHours: 4),
            Student(id: "aa3", name: "Susy", gradeLevel: 11, studyHours: 3),
            Student(id: "aa4", name: "Billy", gradeLevel: 12, studyHours: 5),
            Student(id: "aa5", name: "Jimmy", gradeLevel: 11, studyHours: 1),
            Student(id: "aa6", name: "Johnny", gradeLevel: 10, studyHours: 3),
            Student(id: "aa7", name: "Mikey", gradeLevel: 12, studyHours: 2),
        ]
    }
}

struct StudyTotals: View {

    @ObservedObject var students = GetStudents()

    var onlyUpperClass: Bool

    var studentsFiltered: [Student] {
        switch self.onlyUpperClass {
        case true: return students.items.filter {$0.gradeLevel == 11 || $0.gradeLevel == 12 }
        case false: return students.items
        }
    }

    var body: some View {

        var myArray = getCalcTotals(students: studentsFiltered)

        var rows: Array<String> = []

        return VStack {

            Text("Push Calculated Rows Here??? ")

        }.padding()
    }
}

struct ContentView: View {
    @State private var onlyUpperClass: Bool = false
    var body: some View {
        return VStack {
            StudyTotals(onlyUpperClass: self.onlyUpperClass)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

func getCalcTotals(students: Array<Student>) -> Array<String> {
    let studentArray = students.reduce({ /* here */ })

    var grade: String
    var gradeCount: Int
    var gradeHours: Double? = 0
    var gradeAvg: Double? = 0

    let myArray = ["Count", "Total", "Average"]
    return myArray
}

What I'm needing is this:

A: You can calculate the values inside ForEach as in JavaScript
struct StudyTotals: View {

    @ObservedObject var students = GetStudents()

    var onlyUpperClass: Bool

    var studentsFiltered: [Student] {
        switch self.onlyUpperClass {
        case true: return students.items.filter {$0.gradeLevel == 11 || $0.gradeLevel == 12 }
        case false: return students.items
        }
    }

    var body: some View {

        var countTotal = self.studentsFiltered.count
        var hoursTotal = self.studentsFiltered.reduce(0) { $0 + $1.studyHours }

        return List {
            Group {
                HStack {
                    Text("Count")
                    Text("Hours")
                    Text("Avg")
                }
                ForEach(9...12, id: \.self) { gradeLevel -> AnyView in
                    let count = self.studentsFiltered.filter{ $0.gradeLevel ==  gradeLevel }.count
                    let hours = self.studentsFiltered.filter{ $0.gradeLevel ==  gradeLevel }.reduce(0) { $0 + $1.studyHours }
                    let avg = Float(hours) / Float(count)
                    countTotal += count
                    hoursTotal += hours
                    return AnyView(HStack {
                        Text("Grade\(gradeLevel)")
                        Text("\(count)")
                        Text("\(hours)")
                        Text("\(avg)")
                    })
                }
                HStack {
                    Text("TOTALS")
                    Text("\(countTotal)")
                    Text("\(hoursTotal)")
                    Text("\(Float(hoursTotal) / Float(countTotal))")
                }
            }
        }.padding()
    }
}


text:
Q: Having trouble converting r chisquare goodness of fit test code to python equivalent UCLA has this great site for statistical tests
https://stats.idre.ucla.edu/r/whatstat/what-statistical-analysis-should-i-usestatistical-analyses-using-r/#1sampt
but the code is all in R. I am trying to convert the code to Python equivalents but it is not a straightforward process for some like the chi-square goodness of fit. Here is the R version:
hsb2 <- within(read.csv("https://stats.idre.ucla.edu/stat/data/hsb2.csv"), {
  race <- as.factor(race)
  schtyp <- as.factor(schtyp)
  prog <- as.factor(prog)
})
chisq.test(table(hsb2$race), p = c(10, 10, 10, 70)/100)

My Python attempt is this:
import numpy as np
import pandas as pd
from scipy import stats

df = pd.read_csv("https://stats.idre.ucla.edu/stat/data/hsb2.csv")
# convert to category
df["race"] = df["race"].astype("category")

t_race = pd.crosstab(df.race, columns = 'race')
p_tests = np.array((10, 10, 10, 70))
p_tests = ptests/100
# tried this
stats.chisquare(t_race, p_tests)
# and this
stats.chisquare(t_race.T, p_tests)

but neither stats.chisquare output comes close to the R version. Can anybody steer me in the right direction? TIA

A: chisq.test takes a vector of probabilities; stats.chisquare takes the expected frequencies (docs).
> results = chisq.test(c(24, 11, 20, 145), p=c(0.1, 0.1, 0.1, 0.7))
> results

    Chi-squared test for given probabilities

data:  c(24, 11, 20, 145)
X-squared = 5.028571429, df = 3, p-value = 0.169716919

vs.
In [49]: obs = np.array([24, 11, 20, 145])

In [50]: prob = np.array([0.1, 0.1, 0.1, 0.7])

In [51]: stats.chisquare(obs, f_exp=obs.sum() * prob)
Out[51]: Power_divergenceResult(statistic=5.0285714285714285, pvalue=0.16971691923343338)


text:
Q: How to replace the App_Data\aspnetdb.mdf when migrating to MS Azure? Having a ASP.NET webforms application, I use aspnetdb database created in the SQL server.
When migrating to Azure, is there any way to replace the aspnetdb database by something else so that it would not eat one database from the Azure SQL Database component? Or is the specific database supported somehow as the part of the App Services (Azure component)?
What is the typical replacement of the form of the aspnetdb datababase when working with Azure App Services?
Update: In the original application, I am using two databases in MS SQL Standard Ed. -- typically like company_users (this is the name for the aspnetdb) and company_app for the application tables. I usually create the company_users via a small external application that creates the database, the roles, and also the initial users -- see the shortened code below.
So, it probably would be more straightforward to migrate the two databases to Azure SQL Database, and to use it the same way. On the other hand, one have to pay for the Azure SQL based on the number of databases. While it is fine for the company_app, the company_users is rather small and probably worth to be replaced by something cheaper. This is the motivation for replacing the one for authentication/authorization part of the framework (aspnetdb alias company_users) by something else that would not eat one SQL database.
The shortened source code of my InitUsers.exe:
// ... get the configuration information to be used for...
SqlServices.Install(SQLServerName,
                    SQLServerUser, SQLServerPassword,
                    ASPNETdbName, SqlFeatures.All);
// ... and the roles in the loop...
SqlRoleProvider roleProvider = AModule.GetRoleProvider();
string[] roles = { "admin", "poweruser", /* ... */ };
foreach (var role in roles) {
    if (!roleProvider.RoleExists(role))
        roleProvider.CreateRole(role);
}
// ... and the initial users...
List<string[]> userList = new List<string[]> {
    //      0       1                 2        3        4       5       6
    //      login,  email,            roles,   first,   last    tit.,   phone
    new[] { "nemo", "nemo@ocean.org", "admin", "Nihil", "Nemo", "cpt.", "123 456 789"}
};
foreach (var info in userList) {
    string login = info[0];
    string password = ...;
    string email = info[1];
    string[] rolenames = info[2].Split();
    string first = info[3];
    string last = info[4];
    string title = info[5];
    string phone = info[6];

    AModule.MakeUser(login, password, email, rolenames,
                     first, last, title, phone,
                     true);     // isApproved
}

A:
How to replace the App_Data\aspnetdb.mdf when migrating to MS Azure?

Based on my understanding, you are using SQL Server LocalDB. Azure Web Apps do not install the SQL Server Express. I assume that you could migrate your LocalDB database to SQL Server or SQL Azure. Here is a similar issue, you could refer to it. In order to migrate your database to Azure SQL Database or SQL Server, you could follow the approaches below:

*

*Use SQL Server Management Studio (SSMS), right click your database, then choose "Tasks > Export Data", configure the Data Source and Destination. More details, you could refer to here.

*Use the SSIS Import and Export Wizard from Visual Studio, more details you could refer to here.
Moreover, for creating Azure SQL database, you could follow here. Additionally, if you are using Entity Framework Model First or Entity Framework Code First, you could change your connection string and regenerate your database easily.


text:
Q: Group results under data names with sapply function and plot in R Let's say I have a data which involves 3 separate data. Here is my data;
data<-structure(list(x = structure(list(value = c(2L, 4L, 5L, 6L, 9L,
4L, 3L, 2L, 10L, 6L)), .Names = "value", class = "data.frame", row.names = c(NA,
-10L)), y = structure(list(value = c(2, 2.1, 4, 3, 0, 1.2, 4.2,
3, 4, 9)), .Names = "value", class = "data.frame", row.names = c(NA,
-10L)), z = structure(list(value = c(1, 2, 7, 6, 0.3, 5.4, 4,
3, 6, 7)), .Names = "value", class = "data.frame", row.names = c(NA,
-10L))), .Names = c("x", "y", "z"))

And here is my sample function;
sam<-function(x) {
  ex<-c(3,2,4,5,2)
  z<-data.frame(x)
  y<-as.matrix(sapply(z, as.numeric))
  h<-lapply(c(2,5,10),  function(xx) tapply(y, as.integer(gl(nrow(x), xx, nrow(x)) ), FUN = sum))
  names(h)<-c("min2", "min5", "min10")
  min2<-h[[1]]
  pdf("plots.pdf")
  plot(min2, ex, main="min. compare",
       xlab="Historical Values ", ylab="Disaggregated Values", pch=19, col = "blue")

  dev.off()
  return(h)
}

In the function, I am aggregating values as shown. And then plotting min2 with ex data.
With the code below, I tried to use the function for all data like;
v1<-sapply(data, sam)

But I can not see calculation's name as min2 min5 min10 in result list. And also results are coming complexly, not under the x, y and z
I desire these two;
1) Grouping results under each data name. Like;
[x]              [y]            [z]
min2            min2           min2
min5            min5           min5
min10           min10          min10

2) Plotting the desired ones for all x, y and z  as mentioned above. And export three plots to one pdf or separately.

A: To get the output, like @JonnyPhelps suggested, use lapply instead of sapply. To make the plots and get correlation you need to alter the function:
sam<-function(x) {
  ex<-c(3,2,4,5,2)
  z<-data.frame(x)
  y<-as.matrix(sapply(z, as.numeric))
  h<-lapply(c(2,5,10),  function(xx) tapply(y, as.integer(gl(nrow(x), xx, nrow(x)) ), FUN = sum))
  names(h)<-c("min2", "min5", "min10")
  min2<-h[[1]]
  plot(min2, ex, main="min. compare",
       xlab="Historical Values ", ylab="Disaggregated Values",
pch=19, col = "blue")
COR = cor.test(min2,ex)
LABEL = paste("cor=",signif(COR$estimate,3),"\np=",signif(COR$p.value,3))
mtext(LABEL,side=3,padj=2)
  return(h)
}

The correlation is calculated and you use mtext to place it at the top of the plot. You can play around with padj and adj to get the text where you need.
In your previous function, you called the plot in the function, this overwrites the file with every iteration. To plot all on a pdf, you need to do:
pdf("plots.pdf")
v1<-lapply(data, sam)
dev.off()

Or if you want them on the same page:
pdf("plots.pdf",width=8,height=4)
par(mfrow=c(1,3))
v1<-lapply(data, sam)
dev.off()


text:
Q: Submit Button only saves one input box I'm trying to collect data from input boxes but the submit button only works for one text box. Is there a simple way to fix this? Code:
<?php

if(isset($_POST['textdata']))
{
$data=$_POST['textdata'];
$fp = fopen('data.txt', 'a');
fwrite($fp, $data);
fclose($fp);
}
?>

<!DOCTYPE html>

  <link rel="shortcut icon" href="/favicon.ico" />
  <title>Yeet!</title>

  <form method="post">

    <input type="text" name="textdata">

    <input type="text" name="textdata">

    <input type="text" name="textdata">

    <input type="text" name="textdata">

    <input type="text" name="textdata">

    <input type="submit" name="submit">
  </form>

I just don't want all of my text boxes to have a submit button. Thanks in advance!

A: Every <input> should have an unique name:
<input type="text" name="textdata_a">

<input type="text" name="textdata_b">

$_POST will contain all those keys with the user input as value:
$textdataA = $_POST['textdata_a'];
$textdataB = $_POST['textdata_b'];

A: Your inputs all have the same name, which is why the browser effectively only transmits one of them.
<input type="text" name="textdata">
<input type="text" name="textdata">

Give them different names and access them this way on the PHP side:
<input type="text" name="firstline">
<input type="text" name="secondline">

And in PHP:
$_POST['firstline']; // will contain the data of the first input-element
$_POST['secondline']; // will contain the data of the secondinput-element
// and so on...

If you however need a indefinite number of input fields you can also use an array for that:
<input type="text" name="mytextdata[]">
<input type="text" name="mytextdata[]">

And in PHP:
$_POST['mytextdata']; // will contain the data of ALL the input fields as an array

You could (for example) merge them together like this:
$dataOfAllInputs = implode(PHP_EOL, $_POST['mytextdata']);

However, for such cases using a textarea HTML element might be more reasonable.


text:
Q: Graficar tabla sqlserver con matplotlib Tengo una tabla creada en una BD sql server la cual contiene 4 columnas fecha, x, y, z,
quiero graficarla con matplotlib pero no lo e logrado, les dejo lo que tengo hasta ahora.
import pyodbc
import matplotlib.pyplot as plt

conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=localhost;'
                      'Database=prueba;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor()
cursor.execute('SELECT * FROM dbo.tabla_prueba')
for row in cursor:
    print(row)


text:
Q: Jquery table sorter not working and disable all other javascript I have added Jquery table sorter to my head.
When I add the following to my javascript:
                       $("table").tablesorter();

All of my other Jquery gets disabled and the table sorter does either work.

A: try to open firebug or the console on chrome / ie9.
You have a javascript error which prevents any further execution.
Probably, the tablesorter plugin is not loaded. (<script ... src="wrong here" .../>)
if it is, and your error is inside tablesorter.min.js, you can try to use the not minified version.
ALternatively, your table is empty. If I remember correctly, tablesorter needs a non empty table.


text:
Q: Understanding pipes and redirections in dash Someone asked how to pass the output of two commands as files to another command and they got the answer below.
( cmd1 | ( cmd2 | ( main_command /dev/fd/3 /dev/fd/4 ) 4<&0 ) 3<&0 )

I need to unpack this.
Say I have a text file some_file and I wish to pass it as input to main_command. main_command takes two files as input. If I want to use main_command with some_file and with the output of the command cmd2, one way to do that is
( cmd2 | ( main_command some_file /dev/fd/4 ) 4<&0 )

*

*The "deepest" part of this (i.e. where it all culminates) is
main_command some_file /dev/fd/4. This is simply passing the files
some_file and /dev/fd/4 as arguments to main_command.

*The 4<&0 part says that stdin will point to file descriptor 4.

*cmd2 | connects the output of cmd2 with the input of whatever follows.

*I don't really know what is the function of the parentheses. Do they exist merely for parsing purposes or do they something more?

My questions are:

*

*How do I unpack the command at the beginning of the question?

*What do the parentheses do?

*Is my explanation of the simpler command correct?

Edit: I should have said if my logic is correct, then there's no need to answer 1.

A: This is a pretty complex command. I've answered your questions directly right at the end, but all of this until then is unpacking the command itself. I've tried to be comprehensive so there may be a bit more detail than you need in places.
The parentheses create a subshell:
( x y z )

means to fork a new shell from the current one, to execute x y z in (and then return to the current shell). The subshell inherits everything about the current one, but is a separate process: that means it can have input piped into it, and can have its own environmental changes inside that don't affect the parent.
Every open file has a numeric "file descriptor" associated with it. "File" in this context includes any sort of input or output stream, including real files, sockets, and standard I/O streams. The numbers are handles that can be used directly with the C read function to identify which stream you're talking about, and with the corresponding system call provided by the operating system, along with all the other IO functions.
4<&0 performs a redirection cloning the standard input file descriptor (0) as file descriptor 4. That means FD 0 is copied to 4, not the other way around. In this case, it's modifying the open files for the subshell that precedes the redirection. For the moment, that is just creating another "name" for the input stream. A key part though is that the two names are independent of each other thereafter: FD 4 will always refer to the same stream, even if FD 0 is changed to refer to something else and the two diverge.
/dev/fd/4 is a (non-standard) way for a program to access its own open file descriptors. On Linux, it's a symlink to /proc/self/fd, which reifies the file descriptor table of the current process. A program can open("/dev/fd/4", O_RDONLY) and get a file handle that refers to the stream that this program has on FD 4 (such as 4 itself). As far as the program is concerned, this is just a regular file that can be opened, closed, and read like any other. Because open file descriptors are inherited by subprocesses, main_command has the same file descriptor 4 as the subshell it's inside, and so /dev/fd/4 works there too.
cmd2 | x runs cmd2, and connects its standard output to the standard input - or FD 0 - of x. In your command, x is the subshell expression.

Our overall command
cmd2 | ( main_command /dev/fd/4 ) 4<&0

then has three main parts:

*

*Run cmd2 and pipe its output into ( main_command /dev/fd/4 ) 4<&0.

*Make 4 another name for the stream identified by 0 (standard input) of ( main_command /dev/fd/4 ).

*Run main_command with /dev/fd/4 as an argument, which it will (presumably) open as a file and read from, getting the output of cmd2.

The final effect is that main_command gets a pathname argument it can open and read the output of cmd2 from, exactly as would happen for Bash process substitution main_command <(cmd2): in fact, that would likely give /dev/fd/63 as the argument and otherwise proceed very similarly on the inside.

For the complete command
( cmd1 | ( cmd2 | ( main_command /dev/fd/3 /dev/fd/4 ) 4<&0 ) 3<&0 )

we have nested subshells: that's because we want to make two copies of standard input, but it's two different standard inputs: one is the output of cmd1, which is put into FD 3 after being piped into the larger subshell, and the other is the output of cmd2, which is put into FD 4 after being piped into the innermost subshell. The two 0s both refer to standard input, but each command's standard input is distinct because we have something different piped into it.
That is the most confusing part of the issue, I think. Each command - here, each subshell - has its own standard input, piped in from cmd1 or cmd2, and that unique standard input stream gets aliased to 3 or 4. Those open file descriptors are inherited by the next layer of subshell and child commands, so /dev/fd/3 in the innermost command refers to the same thing it did outside, even though standard input now points to something else.
The outer parentheses are not strictly required, though they make it slightly more robust for some commands and are probably a good practice. The inner ones are: those are used to create a new subprocess that can have its own set of redirections inside it, and its own standard input stream piped in.
The innermost redirection is actually redundant: cmd2 | main_command /dev/fd/3 /dev/stdin would also work, since there's no further change to standard input made.

To address your questions directly:

*

*

How do I unpack the command at the beginning of the question?

The unpacking is the entire post to this point.

*

What do the parentheses do?

The parentheses create a subshell, an independent shell process that can be used like any other command, including having input piped into it, but can perform ordinary shell operations inside, such as redirections.

*

Is my explanation of the simpler command correct?

Partially. 4<&0 says that file descriptor 4 will point to stdin, and importantly to what is called stdin right now - not to the concept of standard input. /dev/fd/4 is a "file" in the "everything is a file sense", but more specifically it's a pathname that, when opened, hands you back your FD 4.


text:
Q: How to count values in an csv file? I would like to write a piece of code which takes information from a .csv file and counts the words and gives me a value of how many times it appeared. I have made the following code but it doesn't work correctly. It only does the first line. How can this be fixed?
import csv
import pandas as pd
from collections import Counter

with open('verbatim.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)

    data=[]
    for line in csv_reader:
        for i in line:
            data.append(i)

    Counter(data)
    data_dict = dict(Counter(data))
    data_processed_dict = {'freq': data_dict}
    df = pd.DataFrame(data_processed_dict)
    df['word'] = df.index
    df.to_csv('dataStatic.csv', index=False)

This is the data I'm trying to evaluate (there is over 400 lines like this):
1   ['investigate', 'wls', 'dash', 'pa', 'issue']
2   ['check', 'vehicle', 'non', 'start', 'assistance']
3   ['check', 'report', 'sound', 'vehicle', 'carry']
4   ['assistance', 'attend', 'vehicle', 'loss', 'electrical', 'system']
5   ['tcu', 'communicate', 'vehicle', 'unable', 'carry', 'campaign', 'n641']
6   ['eml', 'dash']
7   ['customer', 'state', 'bluetooth', 'carly', 'disconnect']
8   ['pdi', 'find', 'vehicle', 'start', 'perform', 'diagnostic', 'note', 'concern', '1', ]

A: Solution:
You are on the right track with:
for line in csv_reader:
    for i in line:
        data.append(i)

But you need to use a dictionary not a list so that it can count every occurrence:
with open('verbatim.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    data = {} #notice the change here
    for line in csv_reader:
        for i in line:
            try:
                data[i] += 1
            except KeyError:
                data[i] = 1
                print(f"{i} added to dictionary")

This will likely save time because you don't have to make the list with 2 for loops then try to use Counter after. It does it all at once.
Example:
Consider this test code:
fileLines = [
['investigate', 'wls', 'dash', 'pa', 'issue'],
['check', 'vehicle', 'non', 'start', 'assistance'],
['check', 'report', 'sound', 'vehicle', 'carry'],
['assistance', 'attend', 'vehicle', 'loss', 'electrical', 'system'],
['tcu', 'communicate', 'vehicle', 'unable', 'carry', 'campaign', 'n641'],
['eml', 'dash'],
['customer', 'state', 'bluetooth', 'carly', 'disconnect'],
['pdi', 'find', 'vehicle', 'start', 'perform', 'diagnostic', 'note', 'concern', '1', ]
]

data = {} #notice the change here
for line in fileLines:
    for i in line:
        try:
            data[i] += 1
        except KeyError:
            data[i] = 1
            print(f"{i} added to dictionary")
print(data)

Output:
{'investigate': 1,
 'wls': 1,
 'dash': 2,
 'pa': 1,
 'issue': 1,
 'check': 2,
 'vehicle': 5,
 'non': 1,
 'start': 2,
 'assistance': 2,
 'report': 1,
 'sound': 1,
 'carry': 2,
 'attend': 1,
 'loss': 1,
 'electrical': 1,
 'system': 1,
 'tcu': 1,
 'communicate': 1,
 'unable': 1,
 'campaign': 1,
 'n641': 1,
 'eml': 1,
 'customer': 1,
 'state': 1,
 'bluetooth': 1,
 'carly': 1,
 'disconnect': 1,
 'pdi': 1, 'find': 1,
 'perform': 1,
 'diagnostic': 1,
 'note': 1,
 'concern': 1,
 '1': 1}

Also printed is:
investigate added to dictionary
wls added to dictionary
dash added to dictionary
pa added to dictionary
issue added to dictionary
check added to dictionary
vehicle added to dictionary
non added to dictionary
start added to dictionary
assistance added to dictionary
report added to dictionary
sound added to dictionary
carry added to dictionary
attend added to dictionary
loss added to dictionary
electrical added to dictionary
system added to dictionary
tcu added to dictionary
communicate added to dictionary
unable added to dictionary
campaign added to dictionary
n641 added to dictionary
eml added to dictionary
customer added to dictionary
state added to dictionary
bluetooth added to dictionary
carly added to dictionary
disconnect added to dictionary
pdi added to dictionary
find added to dictionary
perform added to dictionary
diagnostic added to dictionary
note added to dictionary
concern added to dictionary
1 added to dictionary


text:
Q: Find the angles of triangle We have a triangle $ABC$ where $(AC=BC)$. Point $D$ lay on $AB$ so $AD:BD=3:4$ and $\angle BCD=2\angle ACD$. How to find $cos\left(\angle BAC\right)\:  $/which is equal to $cos\left(\angle ABC\right)\:$/ and$\:cos\left(\angle ACB\right)$?
Any ideas? I would be grateful for any tips!

A: So I drew this and found there are a few tricks in this question and one thing I think is an error.
AC = BC so the triangle is isosceles, yes. Angle ABC = angle BAC because the triangle is isosceles and the cosines of those angles are of course equal.
But we have no info about angle ACB. If its cosine were equal to the others. we'd have three equal angles and an equilateral triangle. That seems to overdetermine the problem and seems to contradict the placement of D. So for the moment let's set angle ACB aside, to find later.
Then we place D on AB so that AD:BD = 3:4
The first thought is to place D between A and B so that AD = 3/7 AB and BD = 4/7 AD. [I suggest you mark your first diagram with AD = 3x and BD = 4x; then of course AB = 7x.]
A second potential positioning is to extend AB in the direction of A and place D outside the triangle in order D, A, B with DA = 3 AB so DB = DA + AB = 4AB. Both positionings are possible within the given constraints so far. Draw a second diagram and look at it. [I suggest you mark your second diagram with AB = w and AD = 3w.].
Now we are given angle BCD = 2 angle ACD.
In version #1 with D between A and B, this means angle BCD = 2y and  angle ACD = y [I suggest you mark these on your first diagram] so  angle ACD = 1/3 angle ACB and angle BCD = 2/3 angle ACB.
In version #2 with D exterior to the triangle, this means angle BCA = angle ACD = 1/2 angle BCD. [I suggest you mark each of angle BCA and angle ACD = z on your second diagram.]
Both diagrams satisfy the constraints of the question so far. Just by looking at it and trying to draw it Version #2 looks more likely but either may or may not be possible.
Now we have two potential solutions diagrammed and we need to calculate some values.
We are looking for cosines so the first temptation would be to calculate the cosine law and see what happens. But that is long and complicated. We may have to do it, but is something simpler available?
I see the sine law and lots of equal sides and other related sides, and some related angles.|
Sine Law: in a triangle PQR with side p ofpposite angle P, side q opposite angle Q, and side r opposite angle R, [Note differences between capitals and lower case!! And note I use names different from the triangles we already have to avoid confusion.]
sin(P)/p = sin(Q)/q = sin(R)/r
OR p/sin(P) = q/sin(Q) = r/sin(R)
Remember that supplementary angles (angles which add to a straight line) have equal sines.
For convenience label AC = BC = a, CD = t, Angle CAB = Angle CBA = u.
In version #1 label angle ADC = s and angle BDC = 180 degrees - s so they have the same sine.
In version #2 label angle ADC = v; we see angle CAD = 180 degrees - u so sin(CAD) = sin u.
Now in Version #1, in  triangle ADC,  sin(s)/a = sin(u)/t = sin(y)/3x
In triangle BDC, sin(s)/a = sin(u)/t = sin(2y)/4x and in the original triangle ABC, sin(u)/a = sin(3y)/7
sin(y)/3x = sin(2y)/4x
Multiply by x = x
sin(y)/3 = sin (2y)/4
Multiply by 4 = 4
Apply the sine addition formula
4/3 sin(y) = 2 sin(y)cos(y)
Divide by 2 = 2
2/3 sin(y) = sin(y)cos(y)
Either sin(y) = 0 or cos(y) = 2/3
Sin(y) = 0 --> y = 0 which is not a real triangle because angles are non-zero.
If cos y = 2/3, we can calculate sin(y) and use summation formulas to get sine and cosines for 2y and the other angles. But a quick reality check first.
Using a calculator, arcsin(2/3) is approximately 41.8 degrees so angle ACB would be approximately 3*41.8 = 125.4 degrees and the other two angles of the triangle would each be 1/2(180 - 125.4) = approximately 27.3 degrees. Yes, this is a feasible triangle.
You can finish this one with summation formulas and the ratios above.
I strongly recommend you also work out Version #2 the same way. It is a valuable thinking exercise. And on tests sometimes the answer is not the one you expect.


text:
Q: Error is null in Mongo? I am working on Mongo and i need to maintain Unique value in field so i done filed as unique but if i submit the the error will be null .
Here is my code  .
var RepositorySchema = new mongoose.Schema({
    folderName: { type: String, unique: true},
    tag: String ,
    ismainFolder: { type: Boolean },
    innerFiles:  [{filename : String,  isFolder: { type: Boolean }, parentfolderId: { type: Schema.ObjectId, ref: 'repository' }, filelocation: { type: String } }],
    innerFolder: [{foldername: {type : String, unique: true}, ismainFolder: { type: Boolean }, parentfolderId: { type: Schema.ObjectId, ref: 'repository' } }],
});

For innerFolder  {foldername: {type : String, unique: true} is not working .


text:
Q: Ordering JSON data in a table I am creating a "leaderboard" page as an external component to a Facebook game.
Basically the app is passing me data through a given JSON response file ('score.json' which contains data objects with three keys: Name, Team, Score), and I am parsing this into an HTML table using the code below:
$(document).ready(function(){
    $.getJSON("score.json",
    function (data) {
        var tr;
        for (var i = 0; i < data.length; i++) {
            tr = $('
');
            tr.append("" + data[i].User_Name + "	");
            tr.append("" + data[i].score + "	");
            tr.append("" + data[i].team + "	");
            $('table').append(tr);
        }
    });
});

What I need to do:

*

*Display these table rows in descending order based on the "score" value.

*Add a "rank" column with a dynamically generated number inserted with each row

I am just a beginner with JavaScript so any help would be much appreciated.
EDIT: Solved. Final code below:
$(document).ready(function(){
    $.getJSON("score.json",
    function (data) {
        var tr;

        data.sort(function(a,b) { return parseFloat(b.score) - parseFloat(a.score) } );

        var rank = 1;

        for (var i = 0; i < data.length; i++) {
            tr = $('
');
            tr.append("" + rank + "	");
            tr.append("" + data[i].User_Name + "	");
            tr.append("" + data[i].score + "	");
            tr.append("" + data[i].team + "	");
            $('table').append(tr);
            rank = rank +1;
        }
    });
});

A: you can use this to sort your array :
json.sort(function(a,b) { return parseFloat(b.score) - parseFloat(a.score) } );

Here is the jsFiddle.


text:
Q: Downgrading MySQL 5.5 > 5.1 - Ubuntu 12.04 I have a Ubuntu 12.04 server running MySQL 5.5.
How can I install MySQL 5.1 or 5.0 on it?
I have tried some commands:
apt-get install mysql-server-5.1
apt-get install mysql-server

None worked...I googled for hints, but no success.
Thank you.

A: Solution provided by STEVEN MARTIN (MySQL expert)
1º Step:
Completely remove old mysql installation:
sudo apt-get purge mysql-server mysql-common

2º Step:
Download MySQL 4.1 sources in order to build it and install.
wget http://mirror.provenscaling.com/mysql/community/source/4.1/mysql-4.1.24.tar.gz

3º Step:
Run these commands to uncompress and build sources and then install:
sudo tar -xvzf mysql-4.1.24.tar.gz --directory=/usr/local/src
cd /usr/local/src/mysql-4.1.24/
sudo groupadd mysql
sudo useradd -g mysql mysql
sudo apt-get install
sudo ./configure --prefix=/usr/local/mysql
sudo make
sudo mkdir /usr/local/mysql
sudo mkdir /usr/local/mysql/include
sudo mkdir /usr/local/mysql/include/mysql
sudo mkdir /usr/local/mysql/lib
sudo mkdir /usr/local/mysql/lib/mysql
sudo mkdir /usr/local/mysql/share
sudo mkdir /usr/local/mysql/man
sudo mkdir /usr/local/mysql/mysql-test
sudo checkinstall
    y
    mysql-server 4.1.24
dpkg -l | grep -i mysql
sudo cp support-files/my-medium.cnf /etc/my.cnf
cd /usr/local/mysql/
pwd
bin/mysql_install_db --user=mysql
sudo chown -R root .
sudo chown -R mysql var
sudo chgrp -R mysql .
bin/mysql --version
bin/mysql_install_db --user=mysql
sudo bin/mysqld_safe user=mysql &

A: Uninstall the currently installed version and download version 5.1 from here.


text:
Q: List of US Time Zones for PHP to use? Is there just a list of time zones for the united states I can use with php? Im using the timezone names from php such as America/Anchorage, php lists time zones here:
http://us.php.net/manual/en/timezones.others.php
I want to display them in a drop down for the user to select but I only need the ones for the US, I dont want to show a bunch that are outside the US.

A: This will automatically get you a list of American timezones:
if (defined('DateTimeZone::AMERICA')) {
    // PHP 5.3+
    $timezoneIdentifiers = timezone_identifiers_list(DateTimeZone::AMERICA);
} else {
    // PHP 5.2
    $timezoneIdentifiers = timezone_identifiers_list();
    $timezoneIdentifiers = array_filter($timezoneIdentifiers, create_function('$tz', 'return preg_match("/^America\//", $tz);'));
}

Note that this will include South American, Canadian etc timezones as well though. You could play around with DateTimeZone::PER_COUNTRY as a filter to timezone_identifiers_list for PHP 5.3 and see if that gets you want you want, or filter the complete list for US/. The best choice is probably to handpick the timezones though.

A: As deceze said, you can use the PER_COUNTRY flag.
$timezone_identifiers = DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, 'US');
foreach($timezone_identifiers as $timezone_identifier) {
  echo "$timezone_identifier\n";
}

Output:
America/Adak
America/Anchorage
America/Boise
America/Chicago
America/Denver
America/Detroit
America/Indiana/Indianapolis
America/Indiana/Knox
America/Indiana/Marengo
America/Indiana/Petersburg
America/Indiana/Tell_City
America/Indiana/Vevay
America/Indiana/Vincennes
America/Indiana/Winamac
America/Juneau
America/Kentucky/Louisville
America/Kentucky/Monticello
America/Los_Angeles
America/Menominee
America/Metlakatla
America/New_York
America/Nome
America/North_Dakota/Beulah
America/North_Dakota/Center
America/North_Dakota/New_Salem
America/Phoenix
America/Shiprock
America/Sitka
America/Yakutat
Pacific/Honolulu

A: Here is a list I found:
Eastern Time    America/New_York
Central Time    America/Chicago
Mountain Time   America/Denver
Mountain Time (no DST) America/Phoenix
Pacific Time    America/Los_Angeles
Alaska Time America/Anchorage
Hawaii-Aleutian America/Adak
Hawaii-Aleutian Time (no DST) Pacific/Honolulu

A: Brute-force way to get ALL timezones per country using PHP's GEOIP. The code is not intended to look nice. You should call this only once and store the result somewhere.
$timezones = array();

foreach (range('A', 'Z') as $i) {
    foreach (range('A', 'Z') as $j) {
        $country = $i . $j;

        foreach (range('A', 'Z') as $k) {
            foreach (range('A', 'Z') as $l) {
                $region = $k . $l;

                if ($timezone = geoip_time_zone_by_country_and_region($country, $region)) {
                    $timezones[$country][$timezone] = true;
                }
            }
        }

        foreach (range(0, 99) as $m) {
            if ($timezone = geoip_time_zone_by_country_and_region($country, sprintf('%02d', $m))) {
                $timezones[$country][$timezone] = true;
            }
        }
    }
}

var_dump($timezones);


text:
Q: How to pass variables to overridden toString() method? Is it possible to pass in a bool variable into an overridden toString() method, so it can conditionally print the object in different formats?

A: You can define overload method of ToString().
public string ToString(bool status){
  //
}

A: The typical pattern for parametrized ToString() is to declare an overload with a string parameter.
Example:
class Foo
{
    public string ToString(string format)
    {
        //change behavior based on format
    }
}

For a framework example see Guid.ToString

A: If you are talking about your own class, you could do the following:
public class MyClass
{
    public bool Flag { get; set; }

    public MyClass()
    {
        Flag = false;
    }

    public override string ToString()
    {
        if (Flag)
        {
            return "Ok";
        }
        else
        {
            return "Bad";
        }
    }
}

And use it
MyClass c = new MyClass();
Console.WriteLine(c); //Bad
c.Flag = true;
Console.WriteLine(c); //Ok
Console.ReadLine();

Your Flag could be some private field and change its value, depending on some inner conditions. It's all up to you.

A: No. An overriding method must have the same signature as the method it's overriding. This means that it can't have any more parameters, since that would change the signature. I would just make a new method for the other format you want.


text:
Q: OpenCV traincascade for LBP training I am trying to create head detector using LBP features in OpenCV, using traincascade utility. The head detector, I hope, will result in something similar to OpenCV's profileface created by Vladim Pivarevsky. I want to recreate the model because current model only handle frontal and left side face.
I follow Naotoshi Seo tutorial and use  dataset from Irshad Ali website. Unfortunately, resulting model performs slowly with lots of false detection.
The traincascade is run as follow:
opencv_traincascade -data "data" -vec "samples.vec" -bg "out_negatives.dat" -numPos 26000 -numNeg 4100 -numStages 16 -featureType LBP -w 20 -h 20 -bt GAB -minHitRate 0.995 -maxFalseAlarmRate 0.3 -weightTrimRate 0.95 -maxDepth 1 -maxWeakCount 100 -maxCatCount 256 -featSize 1

I tried using other dataset, now frontal face from http://fei.edu.br/~cet/facedatabase.html but the result is still same: slow detection and lot of false positives.
Anybody have knowledge or experience in creating cascade haar/lbp model? Please give any suggestion so I can improve the accuracy of the model. I tried using OpenCV built-in model, and the result is good (lbpfrontalface.xml). Thank you so much!

A: The best way is "trial and error"... You really need differents faces, and the greater difference is better. You can take one face and via createsamples do many faces. But this way, you never have good cascade. You should have many different faces, and if they will not be enough, you can increase them through createsamples. For example, you have 500 different faces by createsamples you can do with them 5000, then perhaps cascade will satisfy you.
About start training: to much positive:) or too few negative. You need for example 5000 pos and 2500 neg (pos = 2*neg). At least in my case it was the best choice.

A: It will be slow, relatively as it starts at 20x20 and searches the whole image then gets slightly bigger, searches again etc. - try increasing your sample size to decrease the time to run.
I also noticed you don't have anywhere near as many bg images as positive. Try increasing that to at least the same as your positive and that should help.
I suggest also cracking out the haar features and see if that gives you any results.
everything else seems fine without looking at your input data

A: In short, it's normal to get a lot of false positives after stage 1 of modeling.  You need to take those false positives and add them to the negative dataset and repeat the modeling (stage 2). This is called hard negative mining.  It is essential. You can multiply the false negatives by incrementally rotating them through 360 degrees.
Three other important points: 1) opencv_createsamples is bad for faces; 2) Use negatives that are challenging (suitable); 3) LBP is second rate in many contexts.

*

*Faces are fairly symmetrical and never display a trapezium like distortion in when photographed.  Use very small angles if you must, like 0.02 radians.  Further, you will find when you look at the images in the .vec file that the background fill around the distorted edges looks quite unnatural.

*Not only the number of negatives is important, but the quality of the of the negatives is important.  Faces are smooth compared to many negative images (eg trees, Rocky Mountains etc) so it is relatively easy to distinguish a face from a pine tree at a distance. However, you will get a lot of false positives from smooth surfaces like walls. It is best to include challenging images in the negative dataset. I found that the best background were images of smooth painted plasterboard walls. Take a video whilst walking along some walls, use ffmpeg to chop it up into a heap of images. Again, you can multiply these negatives by incrementally rotating them through 360 degrees, then flip and rotate again.

*Be patient, use HAAR not LBP.
AI is all the rage now, just divide up 100,000 uncropped images into folders for the corresponding classes and start training your model.  However, you may find this approach only gets 98-99% correct classification rate. Way too many false positives.  You will get better results with much less data doing what I said above (whether using HAAR cascades or neural nets).  This is the real data science work: shrewd selection of the negative and positive datasets and the time consuming work in defining the boundary boxes.

A: For any one strugling with flase positives.
Take a look at file traincascade/imagestorage.cpp, at class CvCascadeImageReader::NegReader and methods get and nextImg
I have to rewrite logic of taking negative samples.
When soft negatives are generated they are cut with scaling from background image in step manner fasion in original implementation.
In my case the background samples must be only randomly cut from thise negatives using window size/train size.
In my case it looks like because of scaling larger portions of soft samples into small window, training was stoped to early as it had always blury negative samples and FA passed contrary to real images detected with cascade later


text:
Q: Getting return value from onClickListener of Android Can I set variable into context like session in web development?
Here is my code to in which I am developing an confirmation box as soon as the Android application get started:
package com.example.alertboxandloadingwidgets;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Boolean result = showConfirmationBox("Are you sure you want to do this",
        this);
    }
    public Boolean showConfirmationBox(String messageToShow, final Context context) {
        // prepare the alert box
        AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
        // set the message to display
        alertbox.setMessage(messageToShow);
        // set a positive/yes button and create a listener
        alertbox.setPositiveButton("Yes",
        new DialogInterface.OnClickListener() {
            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context,
                    "'Yes' button clicked", Toast.LENGTH_SHORT)
                    .show();
            }
        });
        // set a negative/no button and create a listener
        alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context, "'No' button clicked",
                Toast.LENGTH_SHORT).show();
            }
        });
        // display box
        alertbox.show();
    }
}

But I want that if the yes button is clicked then it has to return true and if no button is clicked then it has to return false.
But I am not able to do so because return type of onClickListener is void.
Update
But the problem is that I have make it generic means This method I have to write in a CommonUtilities Class From where any of the activity can use this method. So I have to set or reset the value the result parameter from where I am calling this method.

A: Android dialogs are asynchronous, therefore you need to refactor your code to deal with this. I'm guessing you were planning to do something like this:
boolean result = showConfirmation(...);
if(result) {
    //do something
}
else {
    //do something else
}

You can achieve the same result with something like this:
public class MainActivity extends Activity {
    private boolean result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showConfirmationBox("Are you sure you want to do this", this);
    }

    private doOnTrueResult() {
        result = true;
        //do something
    }

    private doOnFalseResult() {
        result = false;
        //do something else
    }

    public void showConfirmationBox(String messageToShow, final Context context) {

        // prepare the alert box
        AlertDialog.Builder alertbox = new AlertDialog.Builder(context);

        // set the message to display
        alertbox.setMessage(messageToShow);

        // set a positive/yes button and create a listener
        alertbox.setPositiveButton("Yes",
        new DialogInterface.OnClickListener() {

            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context,
                    "'Yes' button clicked", Toast.LENGTH_SHORT)
                    .show();
                doOnTrueResult();
            }
        });

        // set a negative/no button and create a listener
        alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {

            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context, "'No' button clicked",
                Toast.LENGTH_SHORT).show();
                doOnFalseResult();
            }
        });

        // display box
        alertbox.show();
    }
}

A: This is how I've always handled data from dialog boxes
alertbox.setPositiveButton("Yes",
    new DialogInterface.OnClickListener() {

        // do something when the button is clicked
        public void onClick(DialogInterface arg0, int arg1) {
            Toast.makeText(context,
                "'Yes' button clicked", Toast.LENGTH_SHORT)
                .show();
               myFunction(item);
        }
    });

private void myFunction(int result){
// Now the data has been "returned" (that's not
// the right terminology)
}

Similarly, use another function for other Button

A: You have to pass the value from onClickListener to a global variable or another method.
As you have correctly recognized the return type of onClickListener is void.
For a more complex solution take a look to this post

A: Create a setter for the result value, and change the value to the selected value in your onClick() methods.
Make showConfirmationBox void ;-)

A: If the function
public Boolean showConfirmationBox(String messageToShow, final Context context)

need to be called in the main thread, you cannot do it. You will never wait for user input on the main thread. That will cause ANR.
If the function can be called in background thread, you can send a message to main thread to show the alert box, and then wait for the result. Make good use of "Handler".

A: You can't do that but u can create a boolean variable and store true if yes and False if no and then u can use that variable accordingly

A: One simple way you could do it:
public class MainActivity extends Activity {
    public static boolean result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showConfirmationBox("Are you sure you want to do this", this);

    }

    public Boolean showConfirmationBox(String messageToShow, final Context context) {
        AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
        alertbox.setMessage(messageToShow);
        alertbox.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context, "'Yes' button clicked", Toast.LENGTH_SHORT).show();
                MainActivity.result = true;
            }
        });

    // set a negative/no button and create a listener
    alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {

        // do something when the button is clicked
        public void onClick(DialogInterface arg0, int arg1) {
            Toast.makeText(context, "'No' button clicked",
            Toast.LENGTH_SHORT).show();
            MainActivity.result = false;
        }
    });

    // display box
    alertbox.show();

    }
}

A: one of the option would be using the
public Button getButton (int whichButton)
Gets one of the buttons used in the dialog.

this Returns
The button from the dialog, or null if a button does not exist.

for more information check the link http://developer.android.com/reference/android/app/AlertDialog.html

A: this may helps you
public class MainActivity extends Activity {
     Boolean mresult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

          Boolean result = showConfirmationBox("Are you sure you want to do this",this);
          Toast.makeText(getApplicationContext(), ""+result, Toast.LENGTH_LONG).show();

    }

     public Boolean showConfirmationBox(String messageToShow, final Context context) {

            AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
            // set the message to display
            alertbox.setMessage(messageToShow);
            // set a positive/yes button and create a listener
            alertbox.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {
                // do something when the button is clicked
                public void onClick(DialogInterface arg0, int arg1) {
                    Toast.makeText(context,
                        "'Yes' button clicked", Toast.LENGTH_SHORT)
                        .show();

                    mresult = true;
                }
            });
            // set a negative/no button and create a listener
            alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
                // do something when the button is clicked
                public void onClick(DialogInterface arg0, int arg1) {
                    Toast.makeText(context, "'No' button clicked",
                    Toast.LENGTH_SHORT).show();

                    mresult = false;
                }
            });
            // display box
            alertbox.show();
            return mresult;
        }

}


text:
Q: Php MySQL import csv returns query, not adding to database I am trying to import a csv file with php and save it to mysql database. Things were working well, and suddenly there seems to be a problem.
When I try to upload the file this is the result (there are 190 fields, but I am just showing a summary of what is returned when I upload):
INSERT INTO `tbl_preschool`(`met_on`, `institution_name`, `slug`, `address`, `landmark`, `area`, `region`, `district_city`) VALUES ('','','','','','1298','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','')

As I said, it was working fine when I checked it once, then all of a sudden things broke down. I don't know how to proceed.

A: Make sure to use right syntax while inserting data, instead of using ' only
change
'','','','','','1298','',*'*,'',

to
'','','','','','1298','',*''*,'',

where * * contains your corrected values

A: You missed one closing quote here '1298','',', change this with
INSERT INTO `tbl_preschool`(`met_on`, `institution_name`, `slug`, `address`, `landmark`, `area`, `region`, `district_city`) VALUES ('','','','','','1298','','','','','','','','','','','','','','','','','','','','','','','','')


text:
Q: Backspace key in Silverlight text box shows previous page in Safari instead of editing text I have a web page with some embedded Silverlight.  In that Silverlight I have a text box.  If I'm using Safari and I hit the backspace key while editing that Silverlight text box, Safari goes back a page as if I had clicked the "show the previous page" button.
What is going on?  It works find in IE, FF and Chrome.  Is there a way that I can fix it?  I don't want to just fix it in my browser.  I'm interested in a fix that'll fix it for all Safari users using our web app.
BTW, I'm using Safari 5.0.3 (7533.19.4)
Thank you,
Aaron

A: It's a bug in Safari for Windows I'm afraid.  It also affects Flash, Microsoft have gone as far as saying Safari on Windows is not compatible with Silverlight (http://www.microsoft.com/getsilverlight/Get-Started/Install/Default.aspx).

A: It's a bug in Safari For Windows 7, It also affects Go! Animate, XtraNormal, ICQ and every kind of Flex websites... So Microsoft have gone as far as saying Safari on Windows is not compatible with Silverlight SDK.. See the URL @ Lee Kowalkowski...


text:
Q: The required column 'int_CommodityPriceId' does not exist in the results. linq to sql public IEnumerable<CommodityPrice> GetAllTimeFrameDaily()
    {
        return _dbprice.ExecuteQuery<CommodityPrice>("SELECT MIN(CommodityPrice.dtm_Date),MAX(CommodityPrice.dtm_Date) FROM CommodityPrice WHERE (CommodityPrice.int_FrequencyId = 1) and int_MarketLocationId in (SELECT [int_LocationId] FROM [Location] where int_LocationTypeId=4  and int_ParentLocationId in (SELECT [int_LocationId] FROM [Location] where int_LocationTypeId=2 and int_ParentLocationId in (SELECT int_LocationId FROM [Location] where int_LocationTypeId = 1 and vcr_LocationEn='Pakistan')))");
    }

i am getting this error The required column 'int_CommodityPriceId' does not exist in the results. any idea why it is doing this. (my dbml file do have the CommodityPriceId column). i am using linq to sql and vs 2010.running it in running file in sql server
commodityprice

int_CommodityPriceId bigint Unchecked
int_CommodityId bigint  Checked
int_SourcesId   int Checked
int_MarketLocationId    int Checked
int_FrequencyId int Checked
flt_Price   float   Checked
flt_PriceUSD    float   Checked

A: This code is attempting to assign the results to a CommodityPrice entity.
In order to do this, it needs to return all of the columns defined in the CommodityPrice entity column properties.. Your query doesn't return ANY of them..
If you just want to return these 2 fields, you'll need a new entity containing just 2 date fields..
TimeFrame
dte_CommodityPriceMinDate  datetime  Unchecked
dte_CommodityPriceMaxDate  datetime  Checked

and the query should populate this instead:
public IEnumerable<TimeFrame> GetAllTimeFrameDaily()
    {
        return _dbprice.ExecuteQuery<TimeFrame>("SELECT MIN(CommodityPrice.dtm_Date) AS dte_CommodityPriceMinDate ,MAX(CommodityPrice.dtm_Date) AS dte_CommodityPriceMaxDate FROM CommodityPrice WHERE (CommodityPrice.int_FrequencyId = 1) and int_MarketLocationId in (SELECT [int_LocationId] FROM [Location] where int_LocationTypeId=4  and int_ParentLocationId in (SELECT [int_LocationId] FROM [Location] where int_LocationTypeId=2 and int_ParentLocationId in (SELECT int_LocationId FROM [Location] where int_LocationTypeId = 1 and vcr_LocationEn='Pakistan')))");
    }


text:
Q: С помощью Stream api Java объединить элементы двух коллекций друг-с-другом Есть 2 коллекции: c1 = Arrays.asList("A", "B", "C") и c2 = Arrays.asList("1", "2", "3"). Подскажите, как с помощью Stream API на Java в 1 строку сделать коллекцию {"A1", "B2", "C3"}?

A: В стандартных стримах почему-то нет операции zip, поэтому приходится прибегать к разврату типа
IntStream
  .range(0, Math.min(c1.size(), c2.size()))
  .mapToObj(i -> c1.get(i) + c2.get(i))
  .forEach(System.out::println);

Но zip есть в Guava
Streams
  .zip(c1.stream(), c2.stream(), (x, y) -> x + y)
  .forEach(System.out::println);

И в StreamEx
StreamEx.of(c1)
        .zipWith(StreamEx.of(c2), (x, y) -> x + y)
        .forEach(System.out::println);


text:
Q: Creating a dynamic table using VB.net Im having this small issue with my code is only creating/showing the last tablecell. I know its probably something small but cant figure out what im doing wrong. Here is my code below.
    Dim tbl As Table = New Table()

    tblrow = New TableRow
    tblcell = New TableHeaderCell
    tblcell.Text = zone_name
    tblcell.HorizontalAlign = HorizontalAlign.Center
    tblrow.Cells.Add(tblcell)
    tbl.Rows.Add(tblrow)

    tblrow = New TableRow
    tblcell = New TableCell
    lblDesc = New Label
    lblDesc.ID = "lbl_" & zone_name
    lblDesc.Text = randomNum
    tblcell.HorizontalAlign = HorizontalAlign.Center
    tblcell.Controls.Add(lblDesc)
    tblrow.Cells.Add(tblcell)

    tbl.Rows.Add(tblrow)

*******edit*************
Public Function add_table(ByVal zone_name As String, ByVal hgt As Integer, ByVal randomNum As Integer, ByVal fontSize As Integer)
    Dim tbl As Table = New Table()

    tbl.ID = "tbl_" & zone_name

    tblrow = New TableRow
    tblcell = New TableCell

    tblcell.Text = zone_name
    tblcell.HorizontalAlign = HorizontalAlign.Center
    tblrow.Cells.Add(tblcell)

    tbl.Rows.Add(tblrow)

    tblrow = New TableRow
    tblcell = New TableCell

    lblDesc = New Label
    lblDesc.ID = "lbl_" & zone_name
    lblDesc.Text = randomNum
    tblcell.HorizontalAlign = HorizontalAlign.Center
    tblcell.Controls.Add(lblDesc)
    tblrow.Cells.Add(tblcell)

    tbl.Rows.Add(tblrow)

    Return tbl
End Function

    tblrow = New TableHeaderRow

    tblcell = New TableHeaderCell
    tblcell.Controls.Add(add_table(zone_name, hgt, randomNum, fontSize))
    tblSeatMap.Rows.Add(tblrow)


text:
Q: Spring "cacheNames" doesn't work with "key" I am trying to configure caching for my methods like this:
@Cacheable(value = USER_ENTITY_1_CACHE, key = "#userId")
public List<MyEntity1> findEntities1(Long userId) {
//...
}

And:
@Cacheable(value = USER_ENTITY_2_CACHE, key = "#userId")
public Set<MyEntity2> findEntities2(Long userId)
{
    //..
}

@Cacheable(value = USER_ENTITY_2_CACHE, key = "#userId")
public Set<MyEntity2> findEntities2(Long userId, boolean deleted)
{
    //..
}

And Evict for this:
@CacheEvict(cacheNames = USER_ENTITY_2_CACHE, key = "#userId", condition = "#userId != null")

Unfortunately, when I invoke any of this method with the same userId, the result for the second one is cached from the first method. This leads to casting problems and confusion.
For instance,
java.util.LinkedHashSet cannot be cast to java.util.List

In other words, when I invoke findEntities1 and then findEntities2, findEntities2 is not invoked, but taken from the cache and fails with class cast exception. The same work if I invoke them in reverse order.
What I really want is that these two caches USER_ENTITY_1_CACHE, USER_ENTITY_2_CACHE don't know about each other and store their own method calls.
I am using RedisCacheManager.
Any ideas what might be wrong here?

A: Remove the key defined explicitly and try
Key will get automatically generated based on the argument based.
@Cacheable(value = USER_ENTITY_1_CACHE)
public List<MyEntity1> findEntities1(Long userId) {
//...
}
And:

@Cacheable(value = USER_ENTITY_2_CACHE)
public Set<MyEntity2> findEntities2(Long userId)
{
    //..
}


text:
Q: Yandex.касса и Android SDK Имеет место быть некий сайт с платными услугами. Онлайн реализованы отношения с кассой через API. Все работает гуд. Однако заказчик пожелал еще и мобильное приложение для оказания тех же услуг. Что имеем: разрабы с помощью SDK получают токен и передают на back. я пытаюсь создать платеж
 $payment = $client->createPayment(
    array('payment_token'=>$contents->payment), uniqid('', true));

где $contents->payment это токен с клиента.
В ответ получаю:
pt-27--------395d{"error":"Failed to build request \"YandexCheckout\\Request\\Payments\\CreatePaymentRequest\": \"Invalid payment amount value: 0.00\""}
Что не так делаю я или что не так с токеном?

A: $payment = $client->createPayment([
  'amount' => [
    'value' => '99.00',
    'currency' => 'RUB',
  ],
  'payment_token' => $contents->payment,
], uniqid('', true));

Поле amount (сумма) является обязательным


text:
Q: What measure in the text is it that is the font size? In LaTeX, you can easily change the font size, using the \fontsize macro (described here) followed by the \selectfont macro. But what is this font size? I changed the font size using the code
\fontsize{10cm}{1.2em}\selectfont

and wrote Mx, and then printed it on my laser printed. I then measured the width of the M and the height of the x; these measured turned out to be approximately 6.9 cm and 3.9 cm, respectively. So none of these turned out to be 10 cm. Not even the diagonal of the M measured 10 cm, even if it wasn't far from it; this measured 9.4 cm.
I then printed the text lql, drew a straight line between the tops of the two ls, and measured the distance from the bottom of the q to the line I had just drawn, thinking that this distance might turn out to be 10 cm. Nope. Only 8.2 cm.
So what measure is it that is 10 cm, that is, where in the text do I find the font size? I want to know this because I need to adjust the vertical distance between the lowest descender and the highest ascender to 0.5 cm on a text I'm going to have at the spine of a book.

A: Generally speaking lead type, the traditional means of printing, consists of individual rectangular pieces of lead with one raised letter at the end. These were assembled into lines, ink applied to the type and then pressed against a piece of paper to obtain the final printed document. The size of a fount is the height of the face of the lead blocks bearing the letters. Of necessity, this must be larger than any of the letters (i.e. ascenders + descenders).

A: I hope it's ok to be super lazy today and just quote a paragraph from https://en.wikipedia.org/wiki/Typeface in full:

The size of typefaces and fonts is traditionally measured in points; point has been defined differently at different times, but now the most popular is the Desktop Publishing point of 1⁄72 in (0.0139 in or 0.35 mm). When specified in typographic sizes (points, kyus), the height of an em-square, an invisible box which is typically a bit larger than the distance from the tallest ascender to the lowest descender, is scaled to equal the specified size. For example, when setting Helvetica at 12 point, the em square defined in the Helvetica font is scaled to 12 points or 1⁄6 in (0.17 in or 4.3 mm). Yet no particular element of 12-point Helvetica need measure exactly 12 points.


text:
Q: Relation between Abstract Data Type and Generic Structure At university we have studied that "ADT combines the same type of data when it is not confined with just one data type perhaps it can take other data types too. So this structure is called generic structure." and I don't know what on earth does that mean???

A: Based on my interpretation of that sentence, it means that ADTs can be adapted to store different types of objects. In Java, ADTs such as TreeSets can store any type that extends Object (so basically no primitives). You can have TreeSet<Integer>, TreeSet<String> and even TreeSet<CustomType>.


text:
Q: Python- Unwanted Unicode characters in printing/extracting text from pdf I am using Python 3.5.2/ Anaconda 4.1.1 to extract text from a pdf: (http://www.mitpressjournals.org/doi/pdf/10.1162/INOV_a_00153) using pypdf2.
I am getting many of these unicode characters in the middle of the printed text that i do not require:
\xc5 \xef \x82 \xef \xac \n.

Can you please help me get rid of these pesky characters?! Thanks for your help!
This is my short piece of code below:
import PyPDF2

pdfFileObj = open('C:\\Users\\HP\\Desktop\\Datasets\\task1_rb.pdf','rb')

pdfReader = PyPDF2.PdfFileReader(pdfFileObj)

num=pdfReader.numPages

for a in range(1,num):

    text=''

    pageObj = pdfReader.getPage(a)

    text=pageObj.extractText().encode('utf-8')

    print(text)

A: You could encode text in ASCII and ignore non-ASCII characters.
Try changing:
text=pageObj.extractText().encode('utf-8')
To:
text=pageObj.extractText().encode('ascii', 'ignore')
I've skimmed the output and it seems to have done the trick.
On a separate point, the range in your for loop is causing you to miss some of the output (unless that's what was intended).
Change for a in range(1,num): to for a in range(0,num):


text:
Q: how to execute several methods with a single click? I want to automatically execute many buttons clicking only on the first, so I used in each button:
webBrowser1.DocumentCompleted +=
    new WebBrowserDocumentCompletedEventHandler(Button2_Click);

However the program crashes. How I can start the execution of several methods one by one (each method must wait until the previous ends)?
to simplify, my first method must load a web page, the second must fill in the fields existing in the page back. when I execute these two methods separately all goes well, but if I execute in a single button the two methods
Method1 ();
method2 ();
it gives me an error on line
HtmlElement = webBrowser1.Document.GetElementById txtbox ("txtbox1");
it does not find the element, so could be the page has not yet been download, so I put each method in a button, and I added to the first button, the line
webBrowser1.DocumentCompleted + = new WebBrowserDocumentCompletedEventHandler (Button2_Click);
so when the webbrowser download page, the button will execute the second, but still the same error: can not find txtbox1.

A: the easy way put the methods calls into your listener's method Button2_Click like this
   {
method1();
    method2();
    method3();
    method4();
}


text:
Q: Matchstick dice game winning strategy so I have been working on this problem for several days now. The fact that I can't find a solution is driving me crazy. I hope you guys can help me out. Here comes the problem:

Let there be 2022 nuts on the table. Two squirrels, Alice and Bob, take turns eating the nuts. To determine the number of nuts they eat
on a given turn, they tip a regular dice over and eat the number that
is on top. The last one unable to make a move loses the game. For
which starting number a can Bob force a win?

I thank anybody who leaves an answer.
Yours,
MathGuy :))))))

A: We can describe the current game state as $(n,d)$ where $n \in \mathbb{N}$ (including zero) is the number of nuts remaining and $d \in \{1,2,3,4,5,6\}$ is the number on the top face of the die, together with the next player to move. Since the rules are symmetric for Alice and Bob, it will be enough to determine whether each $(n,d)$ is a winning or losing state for the current player, assuming ideal play.
The valid moves are from state $(n,a)$ to state $(n-b,b)$ where $a \neq b$ and $a+b \neq 7$. Note the moves from state $(n,a)$ and $(n,7-a)$ are the same, so those two states are always both winning or both losing. So the discussion below will usually just describe the states $(n,1), (n,2), (n,3)$, since the states $(n,6), (n,5), (n,4)$ respectively act the same. (There are still up to six different possible moves from each state, since they will result in different $n$ values. Just the states before and after moves are combined this way.)
As a base case, $(n,a)$ is a losing state if $n$ is smaller than the minimum possible next die face $b$, meaning there is no valid next move. $(0,a)$ (no nuts left) is always a losing state. If $a=1$ or $a=6$ then $b \geq 2$, so $(1,1)$ is a losing state.
Otherwise, a state is a winning state if ANY next move transitions to a losing state. A state is a losing state if EVERY next move transitions to a winning state.
Now let's look at the set of winning and losing $(n,d)$ for each $n$ value until a pattern is suggested.
$(0,d)$ loses.
$(1,1)$ loses. $(1,2)$ and $(1,3)$ win by stepping to $(0,1)$.
$(2,1)$ and $(2,3)$ win by stepping to $(0,2)$. $(2,2)$ wins by stepping to $(1,1)$.
$(3,1)$ and $(3,2)$ win by stepping to $(0,3)$. $(3,3)$ loses since $(2,1)$ and $(1,2)$ win.
$(4,1)$ and $(4,2)$ win by stepping to $(0,4)$. $(4,3)$ loses since  $(3,1)$ and $(2,2)$ win.
$(5,1)$ and $(5,3)$ win by stepping to $(0,5)$. $(5,2)$ loses since $(4,1), (2,3), (1,4)$ all win.
$(6,d)$ can always win by stepping to losing state $(0,6)$ or $(3,3)$. At least one of those must be possible.
$(7,d)$ can always win by stepping to losing state $(1,6)$ or $(3,4)$ or $(4,3)$ or $(5,2)$.
$(8,1)$ and $(8,2)$ win by stepping to $(4,4)$. $(8,3)$ loses since $(2,6), (3,5), (6,2), (7,1)$ all win.
$(9,d)$ loses for any $d$ since $(3,6), (4,5), (5,4), (6,3), (7,2), (8,1)$ all win.
$(10,d)$ can always win by stepping to $(5,5)$ or $(9,1)$.
$(11,d)$ can always win by stepping to $(8,3)$ or $(9,2)$.
$(12,1)$ and $(12,2)$ win by stepping to $(8,4)$ or $(9,3)$. $(12,3)$ loses since $(6,6), (7,5), (10,2), (11,1)$ all win.
$(13,1)$ and $(13,2)$ win by stepping to $(9,4)$. $(13,3)$ loses since $(7,6), (8,5), (11,2), (12,1)$ all win.
$(14,1)$ and $(14,3)$ win by stepping to $(9,5)$. $(14,2)$ loses since $(8,6), (10,4), (11,3), (13,1)$ all win.
$(15,d)$ can always win by stepping to $(9,6)$ or $(12,3)$.
$(16,d)$ can always win by stepping to $(12,4)$ or $(13,3)$ or $(14,2)$.
$(17,1)$ and $(17,2)$ win by stepping to $(13,4)$. $(17,3)$ loses since $(11,6), (12,5), (15,2), (16,1)$ all win.
$(18,d)$ loses for any $d$ since $(12,6), (13,5), (14,4), (15,3), (16,2), (17,1)$ all win.
Looks like the sets of winning $d$ repeat as $n$ increases, with period $9$, starting from $n=3$. Since the future sets of winning $d$ depend only on the previous $6$ sets of winning $d$, the pattern must continue. To be more careful, we could prove by induction that for $n \geq 3$, $(n,d)$ is a losing state if and only if $n \equiv 0 \pmod 9$ or ($n \in \{3,4,8\} \pmod 9$ and $d \in \{3,4\}$) or ($n \equiv 5 \pmod 9$ and $d \in \{2,5\}$).
For the question posed, the initial state before Alice's first move is $(2022, a)$. $2022 \equiv 6 \pmod 9$, so this is a winning state no matter what $a$ is. Alice can always turn the die either to $3$, leaving losing state $(2019,3)$, or to $6$, leaving losing state $(2016,6)$. Unless I've made a mistake or misunderstood the question, Alice can force a win no matter what the value $a$ is, and Bob never can.


text:
Q: How to hide and show my app dialpad number I am using the following code to hide the app from the menu:
 PackageManager p = getPackageManager();
                    ComponentName componentName = new ComponentName(MainActivity2.this,
                            com.example.testdial.MainActivity2.class);
                    p.setComponentEnabledSetting(componentName,
                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                            PackageManager.DONT_KILL_APP);

It's working fine, but when I tried to show the hidden app by using this:
PackageManager p = context.getPackageManager();
            ComponentName componentName = new ComponentName(context,MainActivity2.class);
            p.setComponentEnabledSetting(componentName,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP);

It does not work for me. I searched for a long time in Stack Overflow and Google, but none of the code helped to me. Is there any other way to hide and show my app?


text:
Q: Where is the TFS build process going? Im having a hard time figuring out what the best approach is when designing my build process. It seems Microsoft have turned things around (again).
I am using TFS 2015 and Visual Studio 2015. For earlier versions of TFS I have normally created custom code activities that I plug in to my build definition process file (xaml). I like this approach because it gives me great flexibility and enables me to code .NET classes. I used these guides:
https://msdn.microsoft.com/en-us/library/dd647551(v=vs.120).aspx
http://www.ewaldhofman.nl/post/2010/04/29/Customize-Team-Build-2010-e28093-Part-4-Create-your-own-activity.aspx
In TFS 2015 it seems that there is no documentation on how to create custom code activities. In fact, it seems that Microsoft have changed things and now focuses on scripting languages in stead of custom .NET code: https://msdn.microsoft.com/en-us/Library/vs/alm/Build/steps/index.
I have created a custom code activity and it seems to be working in TFS 2015 (with a few hacks) so it is still possible, but I am nervous that this approach is no longer the way to go.
Can anyone provide information about what is happening here?

A: TFS 2015 introduces new builds, which are web- and script-based, and highly customizable. Meanwhile, TFS 2015 will continue to support the XAML Build templates and controllers.
The new builds are based on a different architecture and run on a completely different system. Currently, you can use both the new builds and agents alongside your XAML builds, controllers, and agents.
Which builds should I use?
If you are new to Team Foundation Server (TFS) and Visual Studio Team Services, you should use this new system. Most customers with experience using TFS and XAML builds will also get better outcomes by using the new system.
The new builds are web- and script-based, and highly customizable. They leave behind many of the problems and limitations of the XAML builds. For example, this new system embraces the diverse set of domain-specific languages (DSLs) that developers used to build the code on their dev machines. We expect this will reduce the chances of running into the "builds fine on my machine but not on the CI server" problem.
If you have heavily customized XAML builds and custom activities, you can continue using those builds until you are ready to port your business logic into scripts that can run in the new builds.
Useful articles for your reference:

*

*https://blogs.msdn.microsoft.com/visualstudioalm/2015/02/12/build-futures/

*https://msdn.microsoft.com/en-us/library/vs/alm/build/feature-overview


text:
Q: Tutorial needed for creating certs with OppenSSL and importing into Glassfish 3.1 I have been tasked with using OpenSSL to create certificates for a webservices project and then importing the certs into glassfish 3.1. I do NOT have access to Apache. (The application that is being created works with username/password verification but we want to add in certificates)
I have googled and read many tutorials, but have yet to get certs working. Does anyone know of the quintessential tutorial to point me to?
I have created the CA, CSR and CRTs using OpenSSL and have tried many ways to get them imported into Glassfish's keystore, but the closest to success I have gotten is the following log message

[#|2012-09-21T16:14:05.859-0500|WARNING|glassfish3.1.1|com.sun.grizzly.config.GrizzlyServiceListener|_ThreadID=17;_ThreadName=Thread-2;|GRIZZLY0007: SSL support could not be configured!
  java.io.IOException: SSL configuration is invalid due to No available certificate or key corresponds to the SSL cipher suites which are enabled.


text:
Q: Getting row-wise percentages for a dataframe Given a dataframe like this:
id v1  v2  v3  v4
1  10  20  60  10
2  10  10  10  70
3  50  25  10  15

I would like to get their rowwise % like this:
id v1  v2  v3  v4  p1   p2   p3   p4
1  10  20  60  10  0.1  0.2  0.6  0.1
2  10  10  10  70  0.1  0.1  0.1  0.7
3  50  25  10  15  0.5  0.25 0.10 0.15

So I need to retain the original variables and create new ones that reflect their relative %, in reality the variables go all the way to 55 so I'm looking for a simple solution that does not require to calculate each value individually.

A: setNames(object = df1[,-1]/rowSums(df1[,-1]),
         nm = gsub("[(v)\\d+]", "p", colnames(df1[,-1])))
#   p1   p2  p3   p4
#1 0.1 0.20 0.6 0.10
#2 0.1 0.10 0.1 0.70
#3 0.5 0.25 0.1 0.15

A: Here is a tidyverse option
library(tidyverse)
left_join(df, df %>%
    gather(k, v, -id) %>%
    group_by(id) %>%
    mutate(frac = v / sum(v), v = NULL, k = str_replace(k, "v", "p")) %>%
    spread(k, frac))
#  id v1 v2 v3 v4  p1   p2  p3   p4
#1  1 10 20 60 10 0.1 0.20 0.6 0.10
#2  2 10 10 10 70 0.1 0.10 0.1 0.70
#3  3 50 25 10 15 0.5 0.25 0.1 0.15

Sample data
df <- read.table(text =
    "id v1  v2  v3  v4
1  10  20  60  10
2  10  10  10  70
3  50  25  10  15", header = T)


text:
Q: GlideRecord ServiceNow Retrieving Int from Field for every record I am new to Service Now and have tried many times to get the data I am looking for. I have a script that grabs all Virtual Machines in our database and takes the CPU count and the core count. I am looking to calculate the kWh usage for all our VMs. The formula is correct and I can run it just fine offline, but when it comes to Gliderecords, I think I am not grabbing the right data. any help would be greatly appreciated. Thank you
var calckWh = function() {
var gr = new GlideRecord('cmdb_ci_server');
var final_result = 0;
var numOfCores;
var numOfCPUs;

gr.addQuery('Model', 'Microsoft Corporation Virtual Machine');
gr.addQuery('CPU core count', '>=', 1);
var qc = gr.addQuery('Install Status', 'Installed');
qc.addOrCondition('Install Status', 'In Use');
gr.query();
while (gr.next()) {
    numOfCores = gr.getValue('cpu_core_count');
    numOfCPUs = gr.getValue('cpu_count');

    for (var j = 0; j < numOfCPUs; j++) {
        var TDP = 165;
        var load0 = 30;
        var load1 = 50;
        var load2 = 80;
        var load3 = 90;
        var load4 = 50;
        var load5 = 30;
        var hours = 4;

        var result = 0;
        var i;
        for (i = 0; i <= 5; i++) {
            var currentLoad = "load" + i;
            result += (numOfCores * TDP * (eval(currentLoad) / 100) * hours) / 1000;
        }
        final_result += result;
    }
}
return final_result;

This script grabs all installed/in-use VMs, and while there is another one in the records, it will run through, grab the current CPU and core count of the VM, then it will do the calculation of the number of times there are CPUs in the VM. it adds all of these calculations up to get the total kWh used for all of our active VMs. The only problem is I should be getting a number between 15,000-16,000, but this results in 229,000. I am not sure why.

A: You cannot use field labels or display values in an addQuery. You must use field names (which are always lower case) and field values. Your first addQuery should look something like this ...
gr.addQuery('model_id', '15e8f8d537a01000deeabfc8bcbe5d46');

... although it is just an example. I do not know the sys_id of "Microsoft Corporation Virtual Machine" in your instance.
If you do not want to hard-code the sys_id of the model, you can dot-walk to the model table like this...
gr.addQuery('model_id.display_name', 'Microsoft Corporation Virtual Machine');

"Installed" and "In Use" are two different names for the same thing, so you probably do not need an "OR" condition. Just use...
gr.addQuery('install_status', '1');

If you need to select multiple values, it is easier to use an "IN" operator
gr.addQuery('install_status', 'IN', '1,4');

I suspect that all your addQuery statements are being ignored, and that you are doing some sort of calculation on all the servers in your instance.
The getValue method always returns a string, regardless of the underlying data type.  Instead of ...
numOfCores = gr.getValue('cpu_core_count');
numOfCPUs = gr.getValue('cpu_count');

it is better to write ...
numOfCores = parseInt(gr.getValue('cpu_core_count'));
numOfCPUs = parseInt(gr.getValue('cpu_count'));

Another problem may be eval(currentLoad). You are not supposed to use eval in a ServiceNow script. You are supposed to use GlideEvaluator or GlideScopedEvaluator.  In this case you do not even need to call eval. Just use an array. It is simpler and more efficient.
var load = [30, 50, 80, 90, 50, 30];

then
result += (numOfCores * TDP * (load[i]) / 100) * hours) / 1000;