text:
Q: alternative of join in a single db table I have a situation where a join of 2 tables is being performed. The record structure is like this:
<person>
 <name>person name1</name>
 <dept>dept1</dept>
 <dept>dept2</dept>
 <dept>dept3</dept>
</person>

<person>
 <name>person name2</name>
 <dept>dept4</dept>
 <dept>dept5</dept>
</person>

Here you can see that a person can belong to more than 1 dept, so a table named person alongwith a table named dept will solve the purpose.
Is there a way that I can manage same data in a single table?
I need a way to have a database table where I can have variable number of columns for storing dept values.
Is there a way with RDBMS to achieve this?
I would appreciate any out of the box ideas as well.
Thanks in Advance

A: You said:

Here you can see that a person can belong to more than 1 dept, so a table named person alongwith a table named dept will solve the purpose.

Think twice that comment. If the relationship between person and dept is owns or visits then is not a one-to-many relationship but rather a many-to-many relationship as a person can own or visit more than one dept and a dept can be owned or visited by more than one person. Given your example, this would translate into this (see dept3):
<person>
 <name>person name1</name>
 <dept>dept1</dept>
 <dept>dept2</dept>
 <dept>dept3</dept>
</person>

<person>
 <name>person name2</name>
 <dept>dept3</dept>
 <dept>dept4</dept>
 <dept>dept5</dept>
</person>

But that, of course, will depend on the requirements, which you haven't mentioned.

Is there a way that I can manage same data in a single table?

I can only think of three ways of doing this (one is more awful than the other):

*

*Add columns up to a needed max (assuming you know there won't be more than X departments per person)

*Leave only two columns, one for person and the other for departments and use it as a multivalued field (yuk!). EG: Use some kind of separator character to identify when a dept finishes and starts the other

*Entity-attribute-value model: This has been discussed many times in StackOverflow. Here is an exmplanation on how to work with it

I need a way to have a database table where I can have variable number of columns for storing dept values.

What is variable in any RDBMS is not actually the columns but rather the rows so, it will always be complicated to handle this.

Is there a way with RDBMS to achieve this?

Any of the major ones will do.
My opinion? Use more tables! This solutions will bring you compolications and a lot of trouble!

A: create table mytable(
    record_id int(11) not null auto_increment,
    ss_num   int(9) not null,
    firstname varchar(20) not null,
    lastname  varchar(20) not null,
    middlename varchar(20),
    deptid     int(11),
    deptname   varchar(5),
    primary key(record_id)
)

You may not need all the fields presented. So edit as you need.


text:
Q: Sort Order of Results on REST query of Datasets I'm trying to understand the order of the results that come through when I execute the following query in WorkBench on Rest api.
/services/data/v54.0/wave/datasets

I'm aware that SOQL queries and such don't apply any kind of sorting unless specified, but not really sure of how I would specify a sort in this query.
Is anybody aware of any default ordering applied on REST response in Salesforce?
If not, is there a method for sorting here? I tried -
/services/data/v54.0/wave/datasets/?order=Descending

But I'm assuming it only applies at the top level which is just a single entry named 'Datasets'.  I need to sort the nested records.
Update - My most recent testing seems to suggest that they are order by 'Last Queried' field.  I opened a lens on a dataset and it moved to the top of the results.
I'd very much appreciate some sort of documentation around this functionality or at least the opinion of an experienced member of this community.
Correction - Even viewing a dataset's properties appears to bump it up the list.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Running function in Qthread - The application will hang I have some problems with threading inside QT.
#include <QCoreApplication>

#include "handler.hpp"

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    Handler* handler = new Handler();
    handler->StartThread();

    return a.exec();
}

What I expect is that with handler->StartThread() statement the function within my thread start to write debug messages and once the internal timer within handler finishes I get the nice line [Press ...] and then a return code of 0. However this is not happening. What I get is:
I WORK...            ( 0x1540 )
Worker has finished. ( 0x6f4  )
I WORK...            ( 0x1540 )
Worker has finished. ( 0x6f4  )
I WORK...            ( 0x1540 )
Worker has finished. ( 0x6f4  )
I WORK...            ( 0x1540 )
Worker has finished. ( 0x6f4  )
Thread stopped.

And of course when I stop the execution of the application, the return code is: -1073741510. Obviously not that nice of a zero.
Anyway here's the rest of the application code:
Handler.hpp
#ifndef HANDLER_HPP
#define HANDLER_HPP

#include <QObject>
#include <QThread>
#include <QDebug>
#include <QTimer>

#include "testclass.hpp"

class Handler : public QObject
{
    Q_OBJECT
public:
    Handler();
    ~Handler();
    void StartThread();

public slots:
    void functionFinished();
    void threadTerminated();

private:
    QTimer*     shutdown;
    QTimer*     timer;
    QThread*    thread;
    MyClass*    worker;
};

#endif // HANDLER_HPP

Handler.cpp
#include "handler.hpp"

Handler::Handler() {
    shutdown        = new QTimer();
    thread          = new QThread();
    timer           = new QTimer();
    worker          = new MyClass();

    worker->moveToThread(thread);
    QObject::connect(thread, SIGNAL(started()), worker, SLOT(runAgain()));
    QObject::connect(timer, SIGNAL(timeout()), worker, SLOT(runAgain()));
    QObject::connect(worker, SIGNAL(iFinished()), this, SLOT(functionFinished()));
    QObject::connect(shutdown, SIGNAL(timeout()), thread, SLOT(quit()));
    QObject::connect(thread, SIGNAL(finished()), this, SLOT(threadTerminated()));

    shutdown->start(20000);
}

Handler::~Handler() {
    QObject::disconnect(thread, SIGNAL(started()), worker, SLOT(runAgain()));
    QObject::disconnect(timer, SIGNAL(timeout()), worker, SLOT(runAgain()));
    QObject::disconnect(worker, SIGNAL(iFinished()), this, SLOT(functionFinished()));
    QObject::disconnect(shutdown, SIGNAL(timeout()), thread, SLOT(quit()));
    QObject::disconnect(thread, SIGNAL(finished()), this, SLOT(threadTerminated()));

    if (shutdown != 0) {
        delete shutdown;
        shutdown = 0;
    }

    if (timer != 0) {
        delete timer;
        timer = 0;
    }

    if (thread != 0) {
        delete thread;
        thread = 0;
    }

    if (worker != 0) {
        delete worker;
        worker = 0;
    }
}

void Handler::functionFinished() {
    qDebug() << "Worker has finished. (" << QThread::currentThreadId() << ")";
    timer->start(5000);
}

void Handler::threadTerminated() {
    qDebug() << "Thread stopped.";
}

void Handler::StartThread() {
    thread->start();
}

MyClass (header - testclass.hpp)
#ifndef TESTCLASS_HPP
#define TESTCLASS_HPP

#include <QTimer>
#include <QObject>

class MyClass : public QObject
{
    Q_OBJECT
public:
    MyClass();

public slots:
    void runAgain();

signals:
    void iFinished();

private:
    void doWork();

};

#endif // TESTCLASS_HPP

MyClass Source - testclass.cpp
#include "testclass.hpp"

#include <QThread>
#include <QDebug>

MyClass::MyClass() {

}

void MyClass::runAgain() {
    doWork();
}

void MyClass::doWork() {
    qDebug() << "I WORK...\t(" << QThread::currentThreadId() << ")";
    emit iFinished();
}

I've previosly read that it's not a good idea to inherit the classes to be ran inside a thread directly from QThread and so I came up with this solution but it still gets fishy though it's pretty nice. I'm open to any recommendation, this is my first time with QT so better to learn now than feel sorry later.
Oh my bad, I forgot the concrete actual question. Why doesn't the execution ends with a nice exit code of 0?

A:
What I expect is that with handler->StartThread() statement the function within my thread start to write debug messages and once the internal timer within handler finishes I get the nice line [Press ...] and then a return code of 0. However this is not happening.

The reason you're not getting a finished command prompt of "[Press ...]" is due to the QCoreApplication and its exec() call. As the Qt docs state: -

Enters the main event loop and waits until exit() is called

So, you've created a second thread, set it to do some work and finish, but the main thread is still running. You need to exit the main thread.

And of course when I stop the execution of the application, the return code is: -1073741510

It sounds like you're killing the main thread with something like "Ctrl+C". Calling QCoreApplication::exit() when your 2nd thread finishes and has cleaned up, should help here.


text:
Q: For each row in one table, find the next row by timestamp with a corresponding uid I'm working in SQL, specifically Amazon Redshift.
Suppose I have data on how users navigate a website:

user_id
timestamp
page_name

1
4:30pm
homepage

3
4:32pm
homepage

4
4:40pm
profile_page

1
4:41pm
profile_page

2
4:48pm
homepage

2
4:59pm
friends_list

4
5:27pm
homepage

3
5:29pm
product_page

4
5:34pm
product_page

1
5:49pm
friends_list

2
5:56pm
product_page

2
5:59pm
homepage

I want to see where users navigate next after reaching the homepage. My final output would look something along the lines of

page_name
frequency

homepage
0

profile_page
1

friends_list
1

product_page
2

because the next place users 3 and 4 went after visiting the homepage was product_page, the next place user 1 went was profile_page, the next place user 2 went was friends_list, and nobody visited the homepage twice in a row.
Is this possible?

A: In the process of trying to formulate my question I may have helped myself find an answer, so posting the solution I've found here:
My current best attempt is to use the LEAD() function
select next_page, count(next_page) as count
from
(select lead(page_name) as next_page
from table
where page_name = 'homepage'
and user_id = lead(user_id)
order by user_id, timestamp)

group by next_page

Suggestions for more optimized approaches are welcome.

A: If you want just the next page, you can use lead().  The correct logic is:
select next_page_name, count(*) as frequency
from (select t.*,
             lead(page_name) over (partition by user_id order by timestamp) as next_page_name
      from t
     ) t
where page_name = 'homepage'
group by next_page_name;

Note:  This does not return 0 counts.  I'm not sure they are useful.  If you have a list of pages that you care about, you can use a left join.  Otherwise, you can use conditional aggregation:
select next_page_name,
       sum( (page_name = 'homepage')::int ) as frequency
from (select t.*,
             lead(page_name) over (partition by user_id order by timestamp) as next_page_name
      from t
     ) t
group by next_page_name;

This also returns NULL if there is no next page.  That does seem useful.


text:
Q: Does magic intensity x2.5 in Master of Magic unbalance the game, eliminating the need for city development and army creation? I started playing Master of Magic two days ago. For the first scenario I chose Tauron and easy level. Initially the game was a bit hard, but I managed to kill two enemies before it crashed due to emulation issues.
For the second attempt I chose a custom hero: Nine books of sorcery, sorcery mastery and conjurer. Normal difficulty.
Then I captured the first sorcery node by magic spirit: moved it to node, summoned as many phantom warriors as I could, killed some guards, escaped an repeated the process. (I could summon a warrior only for 4 mana, so I restored MP by alchemy.)
This gave me enough of a power base to not have to worry about mana for low-level spells. I captured 5-6 cities and the same amount of power nodes without an army.  When I met Tlaloc, my power exceeded his about 10 times.
Does high magic intensity eliminate the need in city development and army creation? (The distant cities can be protected by summoned creatures with word of recall on them.)

A: As the Master of Magic Wikia entry for Nodes indicates the level magic intensity affects how much combat is focused around nodes. This doesn't mean that in the game is necessarily unbalanced by this, it means that you're playing a different style of game.
However Master of Magic is notorious for being an unbalanced game. People love this game because it flexibility.  You have the ability to customize your wizard and choose different play styles, but the effectiveness of builds varies widely. Many are overpowered. Random factors at the start of game will also make a big difference. A powerful rampaging wondering monster encountered early in the game can be a disaster, while starting near a lightly defended node can provide a huge advantage.
So I think the main reason why you were able to steamroll over everything in your second game was a fairly lucky start. This is the kind of thing you have to expect when playing Master of Magic. Increasing the magic intensity probably made exaggerated your lucky start, but it sounds like you would've done well regardless. If Tlaloc had gotten lucky with nodes in his start instead of you maybe you would have had a much different game. (Although the AI in Master of Magic isn't that great either.)


text:
Q: mup deploy killed on DO droplet but no errors in logs :( Even just redeploying a previously successfully deployed app doesn't work. I monitored mup logs -f on a separate terminal while deploying, but nothing ever showed up there. Looks like it doesn't even get to the actual deploy step. I have Node 0.10.31 and Meteor 1.0. Is anyone else having this problem or know how to tackle it?
~# mup deploy

Meteor Up: Production Quality Meteor Deployments
------------------------------------------------

Building Started: /root/TS
Bundling Error: code=137, error:
-------------------STDOUT-------------------

-------------------STDERR-------------------
bash: line 1: 26400 Killed                  meteor build --directory /tmp/2b45aa84-0ffc-4ece-9cf4-aca8500409c3

Actually, the only errors I get relate to bots, but according to my previous posting on SO those errors do not occur during deployment and should not be a problem.

A: It turns out that upgrading from a $5/mo, 500 MB droplet to a $10/mo, 1 GB droplet solved the problem. I previously addressed the memory problem with the $5 droplet using memory swap, but that appears to have run out of mileage. Still, it would have been nice to have errors in the logs to point me in the right directions.


text:
Q: How to read a log file that is updated all the time im trying to create a script that will check the contents of a log file, using windows powershell. The powershell script is checking the log file that is created from another windows application.
The script is the following:
$smtpServer = "MailServer"
$fdate = Get-Date -Format yyyyMMdd
$fname = "C:\tmp\"+$fdate+".log"

$content=Get-Content $fname -wait | where { $_ -match ": exception" }|
foreach {

$line=$_
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "admin@xyz.com"
$msg.ReplyTo = "logs@xyz.com"
$msg.To.Add("logs@xyz.com")
$msg.subject = "Exception"
$msg.body = $line
$smtp.Send($msg)

Write-Host $line
}

The script above is not able to read the new additions of the log file. If for example i have 10 lines in the log file and i start the script now it will check only the current 10 lines. If any new lines are added from the application while the script is running, the script is not able to check the newly added lines!
Any recommendations for a proper solution to that issue? Did anyone tried to do something similar using C/C++ or java?
Thank you

A: Also you can use these: Multithreading with Jobs in PowerShell and PowerShell Multithreading


text:
Q: Combining frequency histograms with density lines I have this code:
`MyData <- read.csv2(
    file="C:/Users/Sysop/Desktop/R_Skaiciavimai/Sezonai.csv",header=T,sep=";")
    MyData
Data_1<-MyData$Sul11P
Data_2<-MyData$Sul11V
Data_3<-MyData$Sul11R
Data_4<-MyData$Sul11Z

D_adjust<-1

Data_1_density<- density(Data_1,adjust = D_adjust,na.rm = TRUE)
Data_2_density<- density(Data_2,adjust = D_adjust,na.rm = TRUE)
Data_3_density<- density(Data_3,adjust = D_adjust,na.rm = TRUE)
Data_4_density<- density(Data_4,adjust = D_adjust,na.rm = TRUE)

Meginio_Vieta<-'Šulinėlis T1-1'
DataBins<-seq(0, 12, by=0.5)

Col_1 <- rgb(1,0,0,0.4)
Col_2 <- rgb(0,0,1,0.4)
Col_3 <- rgb(0,1,0,0.4)

par( mfrow = c( 2, 2 ) )

myhist <- hist(Data_1,breaks=DataBins, plot=FALSE)
multiplier <- myhist$counts / myhist$density
mydensity <- Data_1_density
mydensity$y <- mydensity$y * multiplier[1]
plot(myhist,xlim =c(0,11),col=Col_2,xlab = expression(NH[4]*-N~ "koncentracija     mg/l"),main = Meginio_Vieta, panel.first = grid(nx = 10, ny = 10))
axis(1, at=c(1,3,5,7,9,11))
mtext("Pavasario sezonas",cex = 0.8,adj=0.5, padj=0)
lines(mydensity,col="red", lwd=2)

myhist <- hist(Data_2,breaks=DataBins, plot=FALSE)
multiplier <- myhist$counts / myhist$density
mydensity <- Data_2_density
mydensity$y <- mydensity$y * multiplier[1]
plot(myhist,xlim =c(0,11),col=Col_2,xlab = expression(NH[4]*-N~ "koncentracija mg/l"),main = Meginio_Vieta, panel.first = grid(nx = 10, ny = 10))
axis(1, at=c(1,3,5,7,9,11))
mtext("Vasaros sezonas",cex = 0.8,adj=0.5, padj=0)
lines(mydensity,col="red", lwd=2)

myhist <- hist(Data_3,breaks=DataBins, plot=FALSE)
multiplier <- myhist$counts / myhist$density
mydensity <- Data_3_density
mydensity$y <- mydensity$y * multiplier[1]
plot(myhist,xlim =c(0,11),col=Col_2,xlab = expression(NH[4]*-N~ "koncentracija mg/l"),main = Meginio_Vieta, panel.first = grid(nx = 10, ny = 10))
axis(1, at=c(1,3,5,7,9,11))
mtext("Rudens sezonas",cex = 0.8,adj=0.5, padj=0)
lines(mydensity,col="red", lwd=2)

myhist <- hist(Data_4,breaks=DataBins, plot=FALSE)
multiplier <- myhist$counts / myhist$density
mydensity <- Data_4_density
mydensity$y <- mydensity$y * multiplier[1]
plot(myhist,xlim =c(0,11),col=Col_2,xlab = expression(NH[4]*-N~ "koncentracijamg/l"),main = Meginio_Vieta, panel.first = grid(nx = 10, ny = 10))
axis(1, at=c(1,3,5,7,9,11))
mtext("Žiemos sezonas",cex = 0.8,adj=0.5, padj=0)
lines(mydensity,col="red", lwd=2)

`
Data:
Sul11P  Sul11V  Sul11R  Sul11Z
2,7699  1,4872  0,0725  1,2158
4,9356  3,6808  1,1823  9,5106
0,6507  0,5205  1,3292
1,2734  1,7568  0,1431
1,7568  1,2251  0,541   4,3036
0,3183  1,0875  1,2158  4,0489
1,5058  1,3571  1,4593  0,0279
0,158   0,8682  0,4982  1,0132
9,3601  0,2733  0,9983  1,2511
3,0971  0,5707  1,2232  0,593
4,4951  0,0409  1,1247  0,2175
4,311   0,1208  2,11    3,9392
5,7146  0,0502  1,5307  5,9153
4,3408  1,9105  1,3534  2,4105
1,279   2,3093  1,9105  1,3133
4,2088  1,1108  0,6023  1,2585
2,6863  2,3662  2,2185  1,1952
1,6099  4,5 1,0791  2,1151
1,3998  2,3916  1,4188  1,8873
1,292   3,0035  0,202   1,9337
1,314   2,7165  0,9568
1,56    0,3997  1,0116
1,3049  2,2101

1,7164  0,2647

    3,225

It seems to plot well, result:
http://i60.tinypic.com/2ewzh2u.jpg
But when I try to plot this data:
Sul13P Sul13V  Sul13R  Sul13Z
6,0046  6,5995  0,5242  8,5514
6,4228  7,5475  2,307   8,9529
4,1177  6,4136  2,4543
4,7683  7,225   1,8367  1,6025
4,6289  2,3247  1,6303  2,4985
0,1573  2,8647  1,4946  1,2195
4,8985  3,8333  2,268   3,2923
5,6235  4,034   0,5763  3,1789
10,8008 4,6345  2,5171  1,833
4,5062  4,8334  2,1304  1,8348
3,7998  3,7775  1,1805  0,4294
2,6175  2,8108  1,6824  3,7217
2,861   2,0003  5,5207  3,5823
4,8037  2,8262  4,1555  2,0624
2,6007  4,548   5,7021  2,4506
4,7572  1,0179  3,4402  1,8176
4,0582  4,8054  5,6494  1,5855
2,5487  3   6,16    2,3472
3,6195  3,3706  6,466   1,518
2,7272  2,9802  4,8413  2,324
2,258   5,9216  3,2208  2,9591
2,6914  5,4954  2,765   2,8241
NA  4,6303  2,5414  1,6298
NA  5,7338  0,4271  2,2164
NA  NA  2,8515  1,5328

I get this result:http://i61.tinypic.com/1z6quqg.jpg.
For some reason one density curve is not plotted.
This happens with other similar  data sets I have.
Whats is wrong with my code?


text:
Q: Fetch data from excel sheet using Javascript I am using following code to extract data from excel sheet using javascript. This is working good and after opening the HTML page, getting the data that I want and closing the page, I am unable to open and edit the excel sheet as it is throwing the exception, "File already held by the user and unable to be edited". Is there anyway to handle the closing of excel sheet at the end of the code? Please help me.
<!DOCTYPE html>

Enter Salomon account:

<input type="text" id="myText" name="SalAccount">

<button onclick="myFunction()">Submit</button>


text:
Q: Ubuntu on MSI GE72 6QD freezes except in recovery mode I have installed Ubuntu 15.10 on an MSI GE72 6QD and could not install a working video driver (except the xserver-xorg-video-nouveau with serious limitations).
When I start normally, the machine freezes as the video initialization breaks the keyboard and mouse on a hardware conflict.
If I start in recovery mode, as the startup procedure is in text mode, the machine starts properly, but the video driver does not support a second monitor, which is a deal breaker for my job.

*

*How can I make the machine boot directly in recovery mode. (btw. all boot settings are ignored as recovery mode has its own configuration ¿does that make sense?)

*How/when/where can I find a driver for the nvidia GTX 960M
Please, help
What I have already done:
sudo ubuntu-drivers devices
== /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0 ==
vendor   : NVIDIA Corporation
model    : GM107M [GeForce GTX 960M]
modalias : pci:v000010DEd0000139Bsv00001462sd0000115Bbc03sc02i00
driver   : nvidia-352-updates - distro non-free
driver   : nvidia-352 - distro non-free recommended
driver   : xserver-xorg-video-nouveau - distro free builtin

== cpu-microcode.py ==
driver   : intel-microcode - distro non-free

I have installed both nvidia-352 and nvidia-352-updates and neither works forcing me to recover the original driver with a root shell and recovery mode as both blocked my machine.

A: Edit your boot option and pass "nouveau.blacklist=1 nomodeset" as kernel option.  This would allow Ubuntu 15.10 to boot using the Intel graphics card.
You may then make this kernel argument permanent by editing /etc/default/grub, where you should change the line:-
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

to
GRUB_CMDLINE_LINUX_DEFAULT="nouveau.blacklist=1 quiet splash nomodeset"

Then run
sudo update-grub2

to make the change permanent.  So far, none of the nvidia drivers are working in GE72 6QD.  I have even tried using 361.XX drivers, while the latest stable version is 352.XX.

A: The following solution worked perfectly in my MSI GE72 6QD.

*

*Uninstall all nvidia drivers.

*Change GRUB_CMDLINE_LINUX_DEFAULT to:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash i915.preliminary_hw_support=1 i915.enable_execlists=0 intel_pstate=disable i915.enable_rc6=0"

*Then run sudo update-grub2 to make the change permanent.

*Restart your laptop to witness the proper function of video screen, which is using the Intel GPU now.

*Now you can change the screen brightness using the Fn+Brightness key.           Previous to this change, my screen brightness remained the same always.

*Install the latest nvidia driver using apt-get.  In my case, I installed 361.18 and my Kernel was 4.2.0-27

*Restart now and see nvidia driver in action.  I had checked the functionality by running nvidia-settings.
Reference: https://gist.github.com/ngangat/02c8279e49783328de3a


text:
Q: Given path of a unit vector can we derive the rotation matrix? Let's say a unit vector $\overrightarrow{A}(t)$ in N dimensions is continuously rotated around the origin. It may for example trace out a circle in 3 dimensions or some sort of spiral in higher dimensions.
Can we derive the (infinitessimal) rotation generator $M$ that is rotating the vector over the path $\overrightarrow{A}(t)$? We would have:
$$A(t) = e^{t M } A(0)$$
where $M=-M^T$ is the rotation generator. I wonder if there is a general formula? Perhaps as an infinite series?
Since $M$ has $N(N-1)/2$ components in $N$ dimensions, I suspect that in 3 dimensions one would need at least first and second derivatives of $A(t)$ at a point to work out $M$ and more in higher dimensions.
In 2 dimensions it would be easy. The solution would be
$M=\begin{bmatrix} 0 & \theta \\ -\theta & 0 \end{bmatrix}$ with $\theta=\frac{\dot{A}_0(0)}{A_1(0)}=-\frac{\dot{A}_1(0)}{A_0(0)}$
I think in N dimensions you would set up a series of $N(N-1)$ simultaneous equations:
$$\partial^{k+1} A(t) = M \partial^k A(t)$$
for $k=1..N-1$ then you could solve for the components of $M$. Although this gives twice the number of equations we need. If we had $M\subset GL(D)$ this would be easier as the solution would be:
$$ M_{nm} = \sum\limits_{k=0}^{D-1}(\partial^{k} A_m(0))^{-1} \partial^{k+1} A_n(0)$$
where the inverse is a matrix inverse over the matrix with indices $k$ and $m$.
Not sure how it would change for $M\subset SO(D)$. There would be some identities such as $|A(t)|^2=1$ and all it's derivatives.
Edit (Clarification due to cases pointed out by John Hughes)  There will be certain 'degenerate cases' where it is impossible. For example rotating a 3D vector about it's axis traces a point. Let us ignore those cases! (Or on the other hand, find conditions when it is impossible.)

A: No. Consider the vector $e_1 = \pmatrix{1\\0\\0\\0}$ in 4-space, and the rotation
$$
A(t) = \pmatrix{c & -s & 0 & 0 \\
s & c & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1}
$$
where $c = \cos t$ and $s = \sin t$. The vector $e_1$ traces out the unit circle in the $xy$-plane.
Now look at
$$
B(t) = \pmatrix{c & -s & 0 & 0 \\
s & c & 0 & 0 \\
0 & 0 & c & -s \\
0 & 0 & s & c}
$$
Under the action of $B$, $e_1$ traces out exactly the same path. So from the path, you cannot determine whether you were working with $A(t)$ or $B(t)$.
In three dimensions, if $v$ is the axis of the rotation, you cannot, from the track of $v$, determine the rate of rotation --- not even with multiple derivatives.

A: I assume you define rotation in $\mathbb{R}^n$ as simply an element of $SO(n)$.
$M$ is not unique, unless the image of $A$ spans at least a codimension-1 subspace.  In 2 and 3D, this holds as long as $A'\neq 0$, but in 4D (and hence higher dimensions) you can have $\begin{pmatrix}R_\theta\\&R_\psi\end{pmatrix}$ for any $\psi$ and for $A(0)=e_1$ you only see a rotation in the $e_1,e_2$-plane and know nothing about that is going on in the $e_3,e_4$-plane.
So, let's assume $A(t)$ spans a codimension $\leq 1$ subspace.  We need to solve
$$
A(t)=a_0+e^{it\theta_1}(a_1+ia_2)+e^{-it\theta_2}(a_1-ia_2)+\dots+e^{it\theta_m}(a_{2m-1}+ia_{2m})+e^{-it\theta_m}(a_{2m-1}-ia_{2m})
$$
We have $a_0,a_1,a_2,\dots,a_{2m}$ are mutually orthogonal, $a_1,\dots,a_{2m}$ are nonzero, and $\theta_1,\dots,\theta_m$ are distinct nonzero, in order for $A(t)$ to span a dimension $2m$ (if $a_0=0$) or $2m+1$ (if $a_0\neq 0$) subspace of $\mathbb{R}^n$.  Thus there is a unique linear dependence between $A'(0),A''(0),\dots,A^{(2m+1)}(0)$ (which therefore also works for time $t$).  The coefficients gives you the $\theta_k$ (or rather, $\theta_k^2$), and then looking at kernels give you the $a_k$'s.

If you know the Frenet-Serret formula for a curve in $\mathbb{R}^n$, it is easier to state the result.  Since $e^{tM}$ is a 1-parameter subgroup of isometries and $A(t)=e^{tM}A(0)$, all generalized curvatures are constant.  So with respect to a Frenet-Serret frame
$$
E_1(t)=\frac{A'(t)}{\lvert-\rvert}, E_2(t)=\frac{E_1'(t)-\dots}{\lvert-\rvert},\dots,E_{2m}=\frac{E_{2m-1}'(t)-\dots}{\lvert-\rvert}
$$
we have
$$
(E_i'(t))=\underbrace{\lvert A'(t)\rvert\cdot\begin{pmatrix}0&-\kappa_1(t)\\
-\kappa_1(t)&0&\ddots\\
&\ddots&\ddots&\kappa_{2m-1}(t)\\
&&-\kappa_{2m-1}(t)&0
\end{pmatrix}}_{\text{constant skew-symmetric matrix}}(E_i(t))
$$
But $E_i(t)$ is just another orthonormal basis if $\{A'(t)\mid t\in\mathbb{R}\}$ spans the whole space.  So just conjugate with a change-of-basis to get $M$.  The extension to $a_0\neq 0$ and codimension-1 is obvious.


text:
Q: Delete first element of array before pushing a new one I'm using FireSharp to manage an array of items in a Firebase Realtime database.
I'm trying to implement a kind of queue of 30 messages.
I want to manage only 30 messages and if a new message is received, the first in time order should be deleted.
How can i do it?
In this moment I'm just adding items to the array in this way:
IFirebaseConfig config = new FirebaseConfig{
        BasePath = _RHDLLConfig.firebaseJsonUrl
};
IFirebaseClient client = new FirebaseClient(config);

client.Push("signals", rh);

I want to delete the first element before to push a new one...
The array looks like this:

How can I do it?

A: This will remove the first element of the array
signals = signals.Skip(1).ToArray();


text:
Q: Swing: Is there a simple way to make 1 component ignore the layout manager? I have a JPanel with one component that I want to place in an absolute sense, whereas the rest of the components are placed according to a layout manager.
Is there a simple way to do this?

A: Are you saying you want a component painted over top of all the other components? If so then you would need to use a JLayeredPane.
Why don't you post a SSCCE that demonstrates what you want to do?
You can add components to a frame as you would do normally and make the frame visible. Then you can add this random component and use setBounds on the component. As long as you don't revalidate() the panel or resize the frame we will be able to see how you intend to position this component relative to all the other components.

A: You might also want to look at OverlayLayout, seen here. For some reason it's excluded from the conventional gallery, but it may be of interest.

A: You can do this with only needing one JPanel using MigLayout


text:
Q: Bypass AP Isolate for some devices I have some devices connected to a wireless AP running from hostapd that has AP isolation on. With this, none of the devices can ping each other. However, I would like 2 or more of those devices to be able to ping each other across the WAP. I've done some research but can't seem to find any solution that works for me. Is there a way I can set up a static route or bridge between say 192.168.0.5 and 192.168.0.7 so that they can ping each other over wlan?

A: Allow them to talk through the router/gateway.

*

*If the router is running Linux, enable the "proxy_arp_pvlan" option, so that it'll 'proxy'-answer ARP requests on behalf on hosts on the same subnet. (This will cause problems if the same subnet is shared with an un-isolated ethernet; it should only be done when the AP has a dedicated subnet.)

*Now whenever hosts talk to 192.168.0.7, they'll send all packets to the router's MAC address (due to the proxy-ARP response), and the router will forward the packets back onto the subnet – where the real 192.168.0.7 will receive them (almost as if you didn't have AP isolation).

*Finally, use firewall rules (the 'FORWARD' chain) on the router to control which hosts are allowed to talk to what. In your case, have two rules allowing .5 and .7 to talk to each other, while blocking everything else.


text:
Q: I installed Eclipse IMP, eclipse ide can't open I installed IMP project on eclipse, when i restart Eclipse, OPS.....
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00000000, pid=13303, tid=3020905360
#
# JRE version: 6.0_16-b01
# Java VM: Java HotSpot(TM) Client VM (14.2-b01 mixed mode, sharing linux-x86 )
# Problematic frame:
# C  0x00000000
#
# An error report file with more information is saved as:
# /opt/DEVELOPMENT/eclipse-galileo-SR1/hs_err_pid13303.log
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
Aborted

---------------  S Y S T E M  DETAIL  ---------------
IDE: Eclipse Ganymede
OS:5.0
uname:Linux 2.6.28-17-generic #58-Ubuntu SMP Tue Dec 1 18:57:07 UTC 2009 i686
libc:glibc 2.9 NPTL 2.9
rlimit: STACK 8192k, CORE 0k, NPROC infinity, NOFILE 1024, AS infinity
load average:1.28 1.18 1.14
CPU:total 2 (2 cores per cpu, 1 threads per core) family 6 model 23 stepping 10, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3, sse4.1
Memory: 4k page, physical 2022412k(207344k free), swap 5919912k(5835804k free)
vm_info: Java HotSpot(TM) Client VM (14.2-b01) for linux-x86 JRE (1.6.0_16-b01), built on Jul 31 2009 06:19:30 by "java_re" with gcc 3.2.1-7a (J2SE release)
time: Tue Dec  8 10:51:33 2009
elapsed time: 28 seconds

A: I am not sure IMP is compatible with an eclipse Galileo (3.5).
Their installation page mentions eclipse3.2

A: It is just .metadata crash of eclipse after installed Eclipse IMP


text:
Q: Tkinter Class usage- object() takes no parameters? (WARNING- EXTREME BEGINNER) So I have lifted this code straight from the book: Programming the Raspberry Pi; Getting started with Python by Simon Monk:
from tkinter import *

class App:

    def _init_(self,master):
        frame=Frame(master)
        frame.pack
        Label(frame, text='deg C').grid(row=0, column=0)
        button = Button(frame, text='Convert', command=self.convert)
        button.grid(row=1)

    def convert(self):
        print('Not implemented ')

root = Tk()
root.wm_title('Temp Conv')
app = App(root)
root.mainloop()

However, when I run it it returns the error that
line 18, in <module>
    app = App(root)
TypeError: object() takes no parameters

Any help would be appreciated!

A: you need 2 _ marks before and after init
Thats the format recognized by python as the init function.  since you only put 1 before and after its not recognizing the "init" correctly and thinks its a user created function named "init".  Which means the program thinks there isn't a "init"specified therefore no parameters.


text:
Q: Download source codes from Cognito Forms? Hi I just made a form from cognito form online form maker. I want to download its source code so that i can add php mysql function for it for my database but it cannot be downloaded. Here's the link:
https://www.cognitoforms.com/NegrosOrientalStateUniversity/ListYourPlace

Does any of you here know how to download from cognito. I badly want to use it for our project. thanks!

A: According to their "Terms of Service" you are not allowed to do this:

You may not:
ii. Reverse compile, reverse engineer, reverse assemble, or otherwise attempt, directly or indirectly, to obtain or create source code for the Cognito Site or Services for any reason;

Use Webhooks. It allows application to send data to a third-party.


text:
Q: How to use several variants of input from the user? I want to use this:
Console.WriteLine("What is your name?");
    string userName = Console.ReadLine();

    Console.WriteLine("{0} is a great name!", userName);
    Console.WriteLine("\nWould you like me to tell you a story?");
}

And then have certain commands to be able to detect if they said any variant of the word "yes" or "no" and have all 'Yes' input go into this output:
Console.WriteLine("*Story*");

and all 'No' inputs go into this output:
Console.WriteLine("Would you like me to tell you a joke instead?");

i am relatively new to this, but i understand most of the VERY basic concepts.

A: You already know how to get a string from the user (you're asking for their name).
So do that again after you ask the user your question. Then you can use an if-else block to check what the user typed:
if (answer == "yes") {
  // "yes" stuff here
} else if (answer == "no") {
  // "no" stuff here
} else {
  // "error" stuff here (retry input?)
}

Of course, the user might type "YES" or " Yes ", so you can use Trim() to remove any whitespace around a string, and ToLower() to convert it to lower-case. E.g.
answer = answer.Trim();
answer = answer.ToLower();

Then you don't have to worry about case or white-space any more.
And if you wanted to handle even more cases, you could use some boolean OR conditions:
if (answer == "yes" || answer == "indeed" || answer == "affirmative") {

And I would suggest you put this code into a method, so you can call it more than once without copy+pasting it:
private static bool UserInputAsBoolean(string input) {
    // your code from above here,
    // with "return true;" when the answer was "yes",
    // and "return false;" otherwise.
}

// later..
if (UserInputAsBoolean(input)) {
    // yes, tell a story
} else {
    // no, no story.
}


text:
Q: TwiML: Is there a way to hint Twilio that the user is going to say numbers? I'm writing an IVR application where the user can input a code that consists of numbers. For this I'm using <Gather> with input with the dtmf speech values.
While testing using speech, I've noticed that many times the number is not understood and something else is returned. Is there a way to help Twilio understand that the input is going to be a series of numbers similar to what is done with the normal hints?


text:
Q: Prevent stopping android service I've a Service that is called from an Activity with this code:
startService(new Intent(AMC_Activity.this,CallService.class));

Service is running good for about 20-30 minutes, but after that service stop running, I know that I can use 'foreground' service, but by using that I should show a notification, so, is there any other way to prevent service stop running?

A: I am not sure but i think you are starting your service from UI thread and after that you are putting your in application background so after sometime your activity instance getting lost and that UI thread also killed at that time.
Solution
Create a new Thread and start service with that Thread instead of UI Thread, because service is doing work on that Thread whoever Thread is invoking it.
//This code will be in class body.
private Thread thread1 = new Thread(){
    public void run(){
        startService(new Intent(AMC_Activity.this,CallService.class));
    }
}

//Now this code will be call when you are going to start the service, i.e. Under onCreate()
thread1.start();

It may helpful to you.

A: If you use a TaskManager App on your device you should take care that it doesn't kill your app  and/or service too.


text:
Q: Why is Python not fully object-oriented? I want to know why Python is not fully object-oriented. For example, it does not support private, public, protected access level modifiers.
What are the advantages and disadvantages of this? By these expressions, Python is suitable for what applications (Desktop, Scientific, Web or other)?

A: Guido once said that "we are all consenting adults here". Here's the longer explanation from long ago: http://mail.python.org/pipermail/tutor/2003-October/025932.html
There's an agreement that underscores mean private elements and you should not use them. Unless you know what you're doing and you really want to.
The link also mentions another way to put it in case of Perl:

"a Perl module would prefer that you
  stayed out of its living room
  because you weren't invited, not
  because it has a shotgun."

A: I think Python is designed to be a hybrid.  You can write in object oriented or functional styles.
The hallmarks of object-orientation are abstraction, encapsulation, inheritance, and polymorphism.  Which of these are missing from Python?
Object-orientation is a continuum.  We might say that Smalltalk is the purest of the pure, and all others occupy different places on the scale.
No one can say what the value of being 100% pure is.  It's possible to write very good object-oriented code in languages that aren't Smalltalk, Python included.
Python is useful in all those areas: scientific (NumPy), web (Django), and desktop.

A: I believe Python is more of a very practical, pragmatic language.
Concepts which offer value to the developer are put in, without too much consideration about theological concepts like "proper OO design" and stuff. It's a language for people who have real work to do.
I think Python is suitable for all kinds of environments, though Desktop is a bit difficult due to the lack of a single framework. For all applications it's handy to use a framework,
like NumPy for computational stuff, Twisted or Django for web stuff, and WxWidgets or other for Desktop stuff.

A: What exactly is full object oriented?  Alan Kay said "Actually I made up the term "object-oriented", and I can tell you I did not have C++ in mind.".  Admittedly, he probably did not have python in mind either, but it is worth noting that Smalltalk also protects classes by convention, no mandate.

A: Access modifiers (public, private, protected, etc) are not required for class-based programming. They are just a feature, like multiple inheritance.

A: Python doesn't support strong encapsulation, which is only one of many features associated with the term "object-oriented".
The answer is simply philosophy. Guido doesn't like hiding things, and many in the Python community agree with him.

A: A language is said to Full Objective Oriented if it has no primitive data types. Each data type we need to construct.


text:
Q: Automatically Add/Remove checkboxes when list changes (Google App Script) I'm making a variable list of names. In column B there are names and in column C checkboxes. I would like checkboxes to be added or removed automatically when adding or removing names in column B.
I've been testing this code, but it only put TRUE / FALSE where the checkboxes would go. But I couldn't get it to replace TRUE / FALSE values with checkboxes.
(Sry if my English isn't perfect, I'm from Argentina.)
function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("NamesCheckboxes"); //change this to the name of your sheet
  ui = SpreadsheetApp.getUi();

  //PICK ONE & comment out the other one:
  //var names = ss.getRange("names");//Use this if you are naming the range
  var names = ss.getRange("B4:B");//Use this if you are naming the ranges

  var namesValues = names.getValues(); //Get array of all the names

  //PICK ONE & comment out the other one:
  //var checkboxes = ss.getRange("checkboxes"); //Use this if you are naming the range
  var checkboxes = ss.getRange("C4:C"); //Use this if you want to hard-code your range

  var cbRows = checkboxes.getHeight(); //Get # of rows in the ranges
  var cbValues = checkboxes.getValues(); //Get array of all the checkbox column cell values
  //Logger.log(cbValues);

  var newCBValues = new Array(cbRows); //Create an array to store all the new checkboxes values before we edit the actual spreadsheet

  for (var row = 0; row < cbRows; row++) {
    newCBValues[row] = new Array(0); // Make the array 2 dimensional (even though it only has 1 column, it must be 2D).
    if (namesValues[row] == "" || namesValues[row] == " ") { //If the name cell of this row is empty or blank then...
      newCBValues[row][0] = " "; //Set the value to one space (which will make the cell NOT true or false, and thus NOT display a checkbox).
      //Logger.log("newCBValues[" + row + "][0]: " + newCBValues[row][0]);
    }else{ //otherwise, if the name cell isn't blank...
      if (cbValues[row][0] === true) {
        newCBValues[row][0] = true; //Keep the checkbox checked if it's already checked
      }else{ //If the name cell isn't blank, and it's not true...
        newCBValues[row][0] = false; //Then Keep it or set it to False (an empty checkbox):

      }
    }
  }
  checkboxes.setValues(newCBValues); // now that we have a completed array of our new checkbox values, let's edit the sheet with them!

}

A: Before setting the values you need to convert the range into checkboxes
There are two ways to do it:
1.
checkboxes.setDataValidation(SpreadsheetApp.newDataValidation().requireCheckbox()).setValues(newCBValues);

*

checkboxes.insertCheckboxes().setValues(newCBValues);

A: Thanks to all the people that took the time to help me!
I've used the script for a while now, but it's too slow and sometimes it deselect your selected checkbox when you change your selection fast enough.
So I came with a nice, fast, and easy walkaround, using conditional formating. The checkboxes column that may change the length, has checkboxes for all its height, but in cells where you don't need the checkbox, it hides it with the conditional formatting, making both the background and the checkbox while.
Performance-wise is the fastest solution I've tried, and also it's the simplest one to implement.
I can't believe I didn't think about this solution earlier.
Again, thanks to everyone who came by and took the time to help me.


text:
Q: getting the list of modified/added/deleted files in two different tags using SVN I tried creating a sample repository and created two tags using the below link.
http://artis.imag.fr/~Xavier.Decoret/resources/svn/index.html.
I created two tags namely R1 and R2.
When I use a diff command like
diff ../tags/before-qt/ ../tags/after-qt/ it shows the files which got changed.
But when I try using SVN diff
svn diff -r file:///root/project/tags/before-qt/ file:///root/project/tags/after-qt/
It throws an error
My question:
1) whats the difference between diff and SVN diff commands
2) how can I get the list of modified files in a readable format(tried using summarize also. But its not working)
3) can diff be used on binary files. Will they be listed.


text:
Q: How to update maven project for new chromedriver/selenium with all dependencies With new version of Chromedriver (76) i couldnt use class Actions with moveToElement method.
From what i found out i had to update selenium also. But when i update selenium, ive got err:

cucumber.runtime.CucumberException:
  class steps.MainHooks doesn't have an empty constructor. If you need
  DI, put cucumber-picocontainer on the classpath

Then i updated appium, fluentlenium and so on and so on..
So my question is, what are right versions of dependecies for newest selenium? I am using Fluentlenium, Cucumber, Junit.

A: selenium latest version you can use 3.1XX.X
Made updated version required the dependent dependencies. which can be seen in Compile Dependencies section or in IDE you can go to the pom of selenium, where you can see dependency required for them.
you can see the version on the below URL https://mvnrepository.com/artifact/org.seleniumhq.selenium

A: You need to install the same version of cucumber for the cucumber-picocontainer. Then you must add to CLASSPATH in EnviromentsSetting of Windows, the path to your cucumber-picocontainer-version.jar located in your .m2 repository, for example "C:\Users\Usuario.m2\repository\io\cucumber\cucumber-picocontainer\5.7.0*". Finally, restart the IDE for take the changes. You can check is your CLASSPATH is available in your IDE console, with the command: set CLASSPATH.


text:
Q: AWS Elastic Beanstalk: Custom Cloudwatch Logs not showing despite IAM permissions and custom config I've been having issues setting up custom log file streaming to CloudWatch from my AWS Elastic Beanstalk project. For reference, I've tried the suggestions in "AWS Elastic Beanstalk: Add custom logs to CloudWatch?" to no avail. Essentially, when I download the logs off the host, the log files I want are located at /var/log/containers/api-1c080332ba3f-stdouterr.log, /var/log/containers/nginx-a5057f87f4cf-stdouterr.log, and /var/log/containers/web-0a2e0762e8f0-stdouterr.log (where the numbers change on each update).
I added a new custom log config file in .ebextensions/log.config (following this for reference):
packages:
  yum:
    awslogs: []

files:
  "/etc/awslogs/awscli.conf" :
    mode: "000600"
    owner: root
    group: root
    content: |
      [plugins]
      cwlogs = cwlogs
      [default]
      region = `{"Ref":"AWS::Region"}`

  "/etc/awslogs/awslogs.conf" :
    mode: "000600"
    owner: root
    group: root
    content: |
      [general]
      state_file = /var/lib/awslogs/agent-state

  "/etc/awslogs/config/logs.conf" :
    mode: "000600"
    owner: root
    group: root
    content: |
      [/var/log/containers/nginx-stdouterr.log]
      log_group_name = `{"Fn::Join":["/", ["/aws/elasticbeanstalk", { "Ref":"AWSEBEnvironmentName" }, "var/log/containers/nginx-stdouterr.log"]]}`
      log_stream_name = {instance_id}
      file = /var/log/containers/nginx*

      [/var/log/containers/web-stdouterr.log]
      log_group_name = `{"Fn::Join":["/", ["/aws/elasticbeanstalk", { "Ref":"AWSEBEnvironmentName" }, "var/log/containers/web-stdouterr.log"]]}`
      log_stream_name = {instance_id}
      file = /var/log/containers/web*

      [/var/log/containers/api-stdouterr.log]
      log_group_name = `{"Fn::Join":["/", ["/aws/elasticbeanstalk", { "Ref":"AWSEBEnvironmentName" }, "var/log/containers/api-stdouterr.log"]]}`
      log_stream_name = {instance_id}
      file = /var/log/containers/api*

commands:
  "01":
    command: systemctl enable awslogsd.service
  "02":
    command: systemctl restart awslogsd

I've additionally added this policy to the service and ec2 roles:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:CreateLogGroup",
                "logs:PutLogEvents",
                "logs:DescribeLogGroups",
                "logs:DescribeLogStreams"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

Finally, I don't see any errors in /var/logs/awslogs.log.
Is there any other piece I am missing? Looked through the official documentation with no luck so far.

A: Instead of adding your own policy to the instance role, try adding the CloudWatchAgentServerPolicy managed policy.
I also removed the /etc/awslogs/awslogs.conf file definition when mine worked.
Finally, the agent only seems to create log groups in CloudWatch when lines are written to the log files. Make sure the files you are collecting are getting written to and see if the log groups get created. Good luck!


text:
Q: How to get distinct items and number of occurrences on a nested table? I have a nested table that includes a list of emails, which could be inside several times.
The problem is I need to get the distinct list of items, and the number of times it appears on the list.
|    emails    |
| ------------ |
| a@mail.com   |
| b@mail.com   |
| c@mail.com   |
| d@mail.com   |
| c@mail.com   |
| c@mail.com   |
| a@mail.com   |
| a@mail.com   |
| b@mail.com   |
| b@mail.com   |
| c@mail.com   |

Ideally, my result would be a table or an output that tells me the following:
| Email | Number |
| ---------- | - |
| a@mail.com | 3 |
| b@mail.com | 3 |
| c@mail.com | 4 |
| d@mail.com | 1 |

To select from a table I would use a select statement, but if I try this in my code I get an error "ORA-    00942: table or view does not exist" same with even a simple select from emails table so I'm just guessing     you can't use select on nested tables that way.
The nested table was created like this:
type t_email_type is table of varchar2(100);
  t_emails t_email_type := t_email_type();

and then populated under a loop that adds an email for each iteration of the loop:
t_emails.extend;
t_emails(t_emails.LAST) := user_r.email;

A: I tried to do what you described so far; here you go:
Table that contains e-mail addresses (some of them are duplicates):
SQL> select * from test_mails;

EMAIL
----------
a@mail.com
b@mail.com
c@mail.com
a@mail.com
b@mail.com

Type you created; I think you used type within your PL/SQL procedure. That won't work if it is a function which is supposed to return result of that type because it then must be created at SQL level, so - that's what I'm doing:
SQL> create or replace type t_email_type is table of varchar2(100);
  2  /

Type created.

Function: FOR loop selects e-mail addresses from the table and puts them into t_emails. What you're interested in is what follows in lines #12-14 as it shows how to return the result:
SQL> create or replace function f_test
  2    return t_email_type
  3  is
  4    t_emails t_email_type := t_email_type();
  5    retval t_email_type;
  6  begin
  7    for user_r in (select email from test_mails) loop
  8      t_emails.extend;
  9      t_emails(t_emails.last) := user_r.email;
 10    end loop;
 11
 12    select distinct column_value
 13      bulk collect into retval
 14      from table(t_emails);
 15    return retval;
 16  end;
 17  /

Function created.

OK, let's test it:
SQL> select * from table(f_test);

COLUMN_VALUE
--------------------------------------------------------------------------------
a@mail.com
b@mail.com
c@mail.com

SQL>

Distinct addresses; that's what you asked for.

A: Try it like this:
SET SERVEROUTPUT ON
Create or replace type t_email_type is table of varchar2(100);
/
Declare     --  Outer block - just to populate variable emails of type t_email_type
    Cursor c_emails IS
        Select 'a@mail.com' "EMAIL" From Dual Union All
        Select 'b@mail.com' "EMAIL" From Dual Union All
        Select 'c@mail.com' "EMAIL" From Dual Union All
        Select 'd@mail.com' "EMAIL" From Dual Union All
        Select 'c@mail.com' "EMAIL" From Dual Union All
        Select 'c@mail.com' "EMAIL" From Dual Union All
        Select 'a@mail.com' "EMAIL" From Dual Union All
        Select 'a@mail.com' "EMAIL" From Dual Union All
        Select 'b@mail.com' "EMAIL" From Dual Union All
        Select 'b@mail.com' "EMAIL" From Dual Union All
        Select 'c@mail.com' "EMAIL" From Dual;
    email     VarChar2(100);
    emails    t_email_type := t_email_type();
    i         Number(3) := 0;
Begin
    OPEN c_emails;
    LOOP
        FETCH c_emails Into email;
        EXIT WHEN c_emails%NOTFOUND;
        i := i + 1;
        emails.extend;
        emails(i) := email;
    END LOOP;
    CLOSE c_emails;
    --  Inner block - get distinct emails and number of appearances from variable emails of type t_email_type
    Declare
        Cursor c Is
            Select COLUMN_VALUE "EMAIL", Count(*) "NUM_OF_APPEARANCES"
            From    TABLE(emails)
            Group By COLUMN_VALUE
            Order By COLUMN_VALUE;
            cSet    c%ROWTYPE;
            i       Number(3) := 0;
    Begin
        OPEN c;
        LOOP
            FETCH c Into cSet;
            EXIT WHEN c%NOTFOUND;
            i := i + 1;
            If i = 1 Then
                DBMS_OUTPUT.PUT_LINE(RPAD('EMAIL', 20, ' ') || ' ' || LPAD('NUM_OF_APPEARANCES', 20, ' '));
                DBMS_OUTPUT.PUT_LINE(RPAD('-', 20, '-') || ' ' || LPAD('-', 20, '-'));
            End If;
            DBMS_OUTPUT.PUT_LINE(RPAD(cSet.EMAIL, 20, ' ') || ' ' || LPAD(cSet.NUM_OF_APPEARANCES, 20, ' '));
        END LOOP;
        CLOSE c;
    End;
End;
/*  R e s u l t :
anonymous block completed
EMAIL                  NUM_OF_APPEARANCES
-------------------- --------------------
a@mail.com                              3
b@mail.com                              3
c@mail.com                              4
d@mail.com                              1
*/

Outer block of this code is here just to generate data and to insert it into emails variable that is of type you have defined (t_email_type). You, probably, need just the inner block to get you list of emails with number of appearances within the table type.
SQL that gives you expected result is, actualy, the cursor in the inner block:
Select COLUMN_VALUE "EMAIL", Count(*) "NUM_OF_APPEARANCES"
From    TABLE(emails)
Group By COLUMN_VALUE
Order By COLUMN_VALUE;

Result:

EMAIL
NUM_OF_APPEARANCES

a@mail.com
3

b@mail.com
3

c@mail.com
4

d@mail.com
1

Regards...


text:
Q: The retry strategy using requests is unsuccessful I set a timeout to retry, but in fact I only requested one time and an error was thrown.
What I expect is to retry 2 times after the timeout, and if it still times out, catch the exception and throw an error.
from requests import Session
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util import Retry
from my_exception import MyException
import requests

s = Session()
adapter = HTTPAdapter(
    max_retries=Retry(
        connect=2,
        read=2,
        status_forcelist=[500, 502, 503, 504],
    )
)
s.mount("http://", adapter)
s.mount("https://", adapter)

def get(url):
    try:
        r = s.get(url, timeout=(1, 60))
        r.raise_for_status()
        return r
    except requests.exceptions.RequestException as e:
        if "timed out" in str(e) or "Time-out" in str(e):
            raise MyException(500, "Requests timeout.")
        raise MyException(r.status_code, str(e))

def post(url, data):
    try:
        r = s.post(url, data=data, timeout=(1, 60))
        r.raise_for_status()
        return r
    except requests.exceptions.RequestException as e:
        if "timed out" in str(e) or "Time-out" in str(e):
            raise MyException(500, "Requests timeout.")
        raise MyException(r.status_code, str(e))


text:
Q: How to map keys to a different key I have just started learning VIM using gvim. When I am in the insert mode, and after I have copied stuff ,I usually use CTRL+R + Shift * key combination to paste the stuff in. I would like to map those keys to CTRL+V .
Can you please let me know what I should be doing in my vimrc to achieve my desired goal?
I am on a Windows OS.
Thanks

A: The key combination
:map < c-v > P
should set the paste shortcut to Ctrl+V.
There is a tutorial for creating VIM keymaps here.
You can also try the 3rd chapter of the free book "Learn Vimscript the Hard Way". It gives a very good example of mapping "dd" to "-". I would actually visit this link first and maybe afterwards take the tutorial above.

A: I have 0 Experience with vim on windows. But you can try inoremap <c-v> <c-r>*
And on my linux box, the insert mode Ctrl-v is very important, it can let me input next non-digit literally. It is very handy to input special keys. So if it is same to you, consider to use other keys.


text:
Q: Simulate loading with Thread.Sleep() (Edit - This is for learning purposes only the program is completely pointless)
I'm trying to make it look like my program is loading using Thread.Sleep() with a randomly generated number. It works and it waits the time but for some reason it will not display the history variable on screen until after all of the sleeps have happened.
It should do this

*

*Print logging in...

*Sleep for 5-10 seconds

*print verifying details...

*sleep for 5-10 seconds

*print Logged in.

The reason I am appending the history string is because I want to keep all previous prints on the screen and I'm new to programming so I thought this is the easiest way.
        private void Loading()
    {
        Random rnd = new Random();
        int wait1 = rnd.Next(5000, 10000 );
        history = "Logging in...\n";
        historyLbl.Text = history;
        System.Threading.Thread.Sleep(wait1);
        int wait2 = rnd.Next(5000, 10000);
        history = history + "Verifying Details...\n";
        historyLbl.Text = history;
        System.Threading.Thread.Sleep(wait2);
        history = history + "Logged in.\n";
        historyLbl.Text = history;

    }

A: When you use Thread.Sleep(), it blocks the thread. Like a red light, nothing can move until the block is lifted. In simple Windows Forms applications, the UI thread also runs all of your code. So when you block the thread in a method, you're also blocking the UI.
A nice trick to do something like this is to use the async and await operators, along with Task.Delay()
// Note the change in signature
private async Task Loading()
{
    Random rnd = new Random();
    int wait1 = rnd.Next(5000, 10000 );
    history = "Logging in...\n";
    historyLbl.Text = history;

    await Task.Delay(wait1);

    int wait2 = rnd.Next(5000, 10000);
    history = history + "Verifying Details...\n";
    historyLbl.Text = history;

    await Task.Delay(wait2);

    history = history + "Logged in.\n";
    historyLbl.Text = history;
}

This uses a special language feature that essentially does the waiting on a whole separate thread and comes back to your code when it finishes. That's why the UI won't freeze.
Ok, I'm wrong here. Async and await have allways been a bit mysterious and I guess I just assumed.
Note that anywhere you call this method, you will also need to await it. If you do it on a button click for example, you need to change the button click event handler
// async void is a special pattern for event handlers, to allow them to use async.
// in general you should always use async Task
private async void Button_Click(object sender, EventArgs e)
{
    await Loading();
}

But the bigger question is why would you ever do this? The user never wants to wait longer than they have to. Every once in a while I use Task.Delay() to allow my UI thread to catch up, but thats only for 20ms at most.


text:
Q: Filtering elements while reading .plist array into NSArray First post - hope I'm doing it right!
I have a file, lexicon.plist, containing an array of about 250K words.  I want to load all words of length 'n' into an NSArray.
I know about the NSArray instance method:

*

*(id)initWithContentsOfFile:(NSString *)aPath

but I don't see any way to intervene in the process of reading the file into the NSArray.  The only solution I can see is to first load the entire lexicon into one NSArray, and then run through it in a loop selecting the elements of length 'n'.
I'm very new at Cocoa, but I have come across some methods that perform some sort of iterative task, that accept a "block" of code that is invoked at each iteration.  I was wondering if such a functional variant of initWithContentsOfFile might exist, or how else I might iteratively read an array from a .plist file and filter the elements I'm interested in.
[And if you're wondering if this might be a case of premature optimization - it is ;-)  But I'd still like to know.]

A: If you want to load a filtered selection of a saved data, you should use a SQL repository using SQLite, for example.
Plain files can only be fully loaded in memory.

A: .plist files are basically XML files so you can use an NSXMLParser on it and filter out the elements of interest.


text:
Q: Calculating least number of light fixtures for a run Good afternoon all, I've been using Stack Exchange on a school site, and found it very helpful.  Hopefully my question will be topic appropriate and well phrased.
I am a Project Manager for a Lighting Distributor, and we often need to figure out the number of fixtures of a nominal length to use for a run (ie under the cabinet lighting).  The trick is to get a combination of fixtures that is 0 < length < 6 inches of the total length of the run.
Working in Excel, I would like to input the nominal lengths available (A, B, C, D) and figure out the best possible combination of fixtures.
For example:
RUN = 61

A = 12
B = 18
C = 24
D = 29

OUTPUT = A (+1), C(+2)

I'm sure this has to do with factorials and nCr, but I haven't used these formulas since high school and I'm a bit rusty.  I'm also having trouble figuring out how to link the cells in Excel correctly, so if you know the correct way to do this in Excel, thank you!  But I will try to find answers in an Excel-specific forum as well.
Cheers!
Erin


text:
Q: Densest way to place dominoes/duoplets in an infinite grid with some restrictions Sorry in advance for being bad at explaining things.
Suppose you have a periodic pattern of dominoes and duoplets on an infinite grid that can't overlap. Each domino or duoplet has the ability to "block" one of the squares in its neighborhood (any square that's a king's move away, or equivalently any square that it shares a vertex with). If every square of an occupied square's neighborhood is either blocked or occupied, then that square is considered "crowded". A domino or duoplet cannot crowd one of its own squares. An example of crowding can be seen here, where "blocking" is represented with arrows and the square being crowded is marked with a bright red dot. Each square in the marked square's neighborhood either has an arrow pointing to it from another domino or is occupied by a domino. What is the maximum density infinite pattern of dominoes and duoplets where "crowding" is impossible?
Through trial and error the best pattern I was able to come up with was a pattern of $2\times2$ squares separated by a distance of one, where each square is cut into two dominoes. This pattern has a density of $\frac{4}{9}$ and it can be obtained by translating infinitely many copies of this 3 by 3 square.
Something else I discovered through trial and error to restrict the possible options was that any occupied square can have no more than 6 occupied neighbors. I won't prove it here for the sake of space but it's pretty easy to verify. Using the end of this paper on cellular automata I was able to use this restriction to get an upper bound of $\frac{4}{5}$ on the maximum density, and that's all I've been able to come up with. Any other lower or upper bounds would be appreciated.
Edit:
I managed to improve it to an upper bound of $\frac{2}{3}$. Basically, a necessary condition for crowding to be impossible is that each domino/duoplet has to be able to block a different square. This is because if a domino/duoplet is unable to block a square that isn't already blocked or occupied, that's basically the same thing as saying the squares in that domino/duoplet are crowded. That means there must be at least one unoccupied square for every domino/duoplet (one unoccupied square per two occupied squares), so the density can't be more than $\frac{2}{3}$.
Edit 2: problem variants + additional constraints
An interesting sub-problem is trying to find the densest pattern without crowding where there are a limited number of colors for the dominos/duoplets to be colored with, and no domino/duoplet can be the same color as a domino/duoplet in its neighborhood (this is pretty basic graph theory).
Another version of the problem you could consider is where individual squares are used instead of dominos/duoplets. This lowers the amount of possibilities but it also means the pattern can't be as dense, since each occupied square can block a square, as opposed to each pair of occupied squares.
Here's a summary of the best solutions so far to three different variants of this problem (colors are marked with letters).
Main Problem (3+ colors): density 1/2
. . A B . . A B
. . A C . . A C
. . B C . . B C
. . B A . . B A
. . C A . . C A
. . C B . . C B

2 colors: density 4/9
. A A . A A
. B B . B B
. . . . . .
. A A . A A
. B B . B B
. . . . . .

Single squares: density 1/3
. . A . . A
. . B . . B
. . A . . A
. . B . . B

A: I'm not 100% sure I understand your problem setting, but how about this pattern?
. . A B . . G H
. . A B . . G H
. . C D . . J K
. . C D . . J K
. . E F . . L M
. . E F . . L M

Consider one of the squares of the C domino.  It has $3$ spaces to its Northwest, West, Southwest.  Since only dominoes A and E can block those spaces (C cannot block those spaces for the purpose of crowding a C-square), together they can only block $2$ of the $3$, meaning that C-square is not crowded.
This pattern obviously repeats with a density of $1/2$.

any occupied square can have no more than 6 occupied neighbors.

Can you elaborate on this?  Clearly $7$ is not OK.  But is $6$ actually OK?  I haven't gone through all possibilities but so far I haven't come up with a case where an occupied square has $6$ occupied neighbors but cannot be crowded.


text:
Q: Skype for Business 2015 trusted application hosted on a standalone server? I was looking for information on how to run a Skype for Business 2015 trusted application on a standalone (aka workgroup joined) server. The need is for development reasons only: my dev workstation is in a workgroup and I cannot join it to the domain running the Skype infrastructure. I believe I read somewhere that this should be possible but my attempt to find an article/blog post describing any required steps to make it work failed.

A: It's possible, you just need to follow the same instructions as a normal domain joined machines.  I would only setup for a manually provisioned application as a auto provisioned application requires your machine to setup to replicate the topology. (This can be done, but is not nice - you can follow the Edge server setup as a example of this type of setup on a non-domain joined machine).
You machine needs to setup as a application pool within the SfB topology.
For a non-domain joined machine you will most likely have to install the required certificates mainly.
You will need to install the CA certificate for the domain that SfB uses into your machines trusted root and you will also need to get the domain to generate a certificate for you machine and install it into your certificate store so that your UCMA application to select and use it in the UCMA setup.
Once your machine is setup as a application pool with the required certificates. Then you just need to setup the trusted application within the SfB topology.
All of this is just easier with a domain joined machine as you can only do a lot of these steps on a domain joined machine (or on the SfB server itself).
Once the SfB topology is setup then developing the UCMA application on your machine it possible.


text:
Q: How does one indicate the corresponding author when using the authblk package? This question is not a duplicate of How to print the corresponding author, because that question is asking specifically how to make the corresponding author's name appear to the left of the complete list of authors, while also appearing in the complete list of authors.
I'd like to know the simplest, most standard way to indicate the corresponding author when using the authblk package.  I've googled a fair amount and have not found the answer.  If it's relevant, I'll be using the titlepage option, as in \documentclass[titlepage]{article}.
Here's a minimal example where the corresponding author is not indicated.  So I'd like to know how to alter this to indicate the corresponding author.
\documentclass[titlepage]{article}
\usepackage[affil-it]{authblk}
\usepackage[english]{babel}
\usepackage{blindtext}

\title{An efficient method for exploiting midichlorians in weak life-forms}

\author[1]{Darth Vader}
\author[2]{Darth Sidious}

\affil[1]{%
  Office of the Supreme Commander of the Imperial Forces,
  The Galactic Empire, The Bridge, Executor}
\affil[2]{%
  Order of the Sith Lords, LiMerge Power Building, The Works, Coruscant}

\begin{document}

\maketitle
\blindtext
\end{document}

The following code produces the screenshot later on, a screen of the log is attached as well.
\listfiles
\documentclass[titlepage]{article}
\usepackage[affil-it]{authblk}
\usepackage[english]{babel}
\usepackage{blindtext}

\title{An efficient method for exploiting midichlorians in weak
life-forms}

\author[1]{Darth Vader\thanks{corresponding author}}
\author[2]{Darth Sidious}

\affil[1]{%
    Office of the Supreme Commander of the Imperial Forces,
The Galactic Empire, The Bridge, Executor}
\affil[2]{%
    Order of the Sith Lords, LiMerge Power
Building, The Works, Coruscant}

\begin{document}

\maketitle
\blindtext
\end{document}

You can see the number 1 is repeated as a superscript.
If I add \listfiles to the document, here is the log I get:

A: You can do it using \thanks , but if you are using the titlepage option (as in \documentclass[titlepage]{article}) then you should include the line \renewcommand{\thefootnote}{\fnsymbol{footnote}} in the header to make the footnote marker be an asterisk.  We can also place the line \renewcommand{\thefootnote}{\arabic{footnote}} after \maketitle, to undo the global change.  Here is a MWE:
\documentclass[titlepage]{article}
\usepackage[affil-it]{authblk}
\usepackage[english]{babel}
\usepackage{blindtext}

\renewcommand{\thefootnote}{\fnsymbol{footnote}}
\title{An efficient method for exploiting midichlorians in weak life-forms}

\author[1]{Darth Vader \thanks{Corresponding author}}
\author[2]{Darth Sidious}

\affil[1]{%
  Office of the Supreme Commander of the Imperial Forces,
  The Galactic Empire, The Bridge, Executor}
\affil[2]{%
  Order of the Sith Lords, LiMerge Power Building, The Works, Coruscant}

\begin{document}

\maketitle
\renewcommand{\thefootnote}{\arabic{footnote}}
\blindtext
\end{document}

A: I found this question when googling for setting corresponding authors in ACM templates. This is how to set corresponding authors in an ACM template:
\author{Author 1}
\affiliation{\institution{Affiliation}}
\email{email}
\authornote{Corresponding authors}

\author{Author 2}
\affiliation{\institution{Affiliation}}
\email{email}
\authornotemark[1]

\author{Author 3}
\affiliation{\institution{Affiliation}}
\email{email}

Here, author 1 and 2 are both set as corresponding authors, but author 3 isn't. Further explanation can be found here: https://www.acm.org/binaries/content/assets/publications/consolidated-tex-template/acmart.pdf

A: This is more a workaround than an official solution I guess. But depending on the journal's author-guidelines for your manuscript this formatting might look  more appropriate.
It includes the indicator for the corresponding author as an affiliation.
Example code:
\listfiles
\documentclass[titlepage]{article}
\usepackage[affil-it]{authblk}
\usepackage[english]{babel}
\usepackage{blindtext}

\title{An efficient method for exploiting midichlorians in weak life-forms}

\author[1,*]{Darth Vader}
\author[2]{Darth Sidious}

\affil[1]{Office of the Supreme Commander of the Imperial Forces, The Galactic Empire, The Bridge, Executor}
\affil[2]{Order of the Sith Lords, LiMerge Power Building, The Works, Coruscant}
\affil[*]{Corresponding author: Darth Vader, darth@vader.deathstar}

\begin{document}

\maketitle
\blindtext
\end{document}

Example picture:

A: For me this solution taken from here worked for an elsarticle document:
\author[affiliation]{Corresponding Author Name\corref{cor1}}
\ead{Corresponding Author Email Address}
\cortext[cor1]{Corresponding author}


text:
Q: Crash due index out of range -- although I'm sure index is not out of range I have a parent view whose child view is any given index of an array. The index of the array is scrolled through by tapping buttons that increment or decrement the index which is stored in a State property.
However when the view is first initialized I get a crash, even though the State's initial value is always 0.
What is going on?
Code can be copied and pasted to reproduce error
import SwiftUI

struct ContentView: View {
    @State private var shouldShowQuotes = false
    var body: some View {
        ZStack {
            Color.orange
            VStack {
                Button(action: showQuotes){
                    Text("Get Quotes").bold()
                        .frame(maxWidth: 300)
                }
                   //  .controlProminence(.increased) //Safe to uncomment if Xcode 13
                    // .buttonStyle(.bordered)
                    // .controlSize(.large)
            }
            .fullScreenCover(isPresented: $shouldShowQuotes) {
                QuoteScreen()
            }
        }.ignoresSafeArea()
    }
    private func showQuotes() {
        self.shouldShowQuotes.toggle()
    }
}

struct QuoteScreen: View {
    @State private var quoteIndex = 0
    var currentQuote: Quote {
        return dummyData[quoteIndex]
    }
    var body: some View {
        ZStack {
            Color.orange
            VStack {
                QuoteView(quote: currentQuote)
                Spacer()
                HStack {
                    Button(action: degress) {
                        Image(systemName: "arrow.left.square.fill")
                            .resizable()
                        .frame(width: 50, height: 50)
                    }
                    Spacer()
                    Button(action: progress) {
                        Image(systemName: "arrow.right.square.fill")
                            .resizable()
                        .frame(width: 50, height: 50)
                    }
                }
                .padding(28)
                    //.buttonStyle(.plain) Safe to uncomment if Xcode 13

            }
        }.ignoresSafeArea()
    }
    private func progress() {
    quoteIndex += 1
    }

    private func degress() {
        quoteIndex -= 1
    }
}

struct QuoteView: View {
    @State private var showQuotes = false
    let quote: Quote
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 25)
                .stroke(lineWidth: 2)
            VStack {
                Text(quote.quote)
                frame(maxWidth: 300)
                Text(quote.author)
                    .frame(maxWidth: 300, alignment: .trailing)
                    .foregroundColor(.secondary)
            }

        }.navigationBarHidden(true)
        .frame(height: 400)
            .padding()
    }
}

let dummyData = [Quote(quote: "The apple does not fall far from the tree", author: "Lincoln", index: 1),
                Quote(quote: "Not everything that can be faced can be changed, but be sure that nothing can change until it is faced", author: "Unknown", index: 2),
                 Quote(quote: "Actions are but intentions", author: "Muhammad", index: 3)
    ]

struct Quote: Codable {
    let quote: String
    let author: String
    let index: Int
}

A: When using arrays you always have to check that the element at the chosen index exist. This is how
I tested and modify your code to make it work.
(note: although this is just a test with dummyData, you need to decide if you want to scroll through the array index, or the Quote-index value, and adjust accordingly)
import SwiftUI

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

let dummyData = [
    Quote(quote: "the index zero quote", author: "silly-billy", index: 0),
    Quote(quote: "The apple does not fall far from the tree", author: "Lincoln", index: 1),
    Quote(quote: "Not everything that can be faced can be changed, but be sure that nothing can change until it is faced", author: "Unknown", index: 2),
    Quote(quote: "Actions are but intentions", author: "Muhammad", index: 3)
]

struct ContentView: View {
    @State private var shouldShowQuotes = false
    var body: some View {
        ZStack {
            Color.orange
            VStack {
                Button(action: showQuotes){
                    Text("Get Quotes").bold()
                        .frame(maxWidth: 300)
                }
                //  .controlProminence(.increased) //Safe to uncomment if Xcode 13
                // .buttonStyle(.bordered)
                // .controlSize(.large)
            }
            .fullScreenCover(isPresented: $shouldShowQuotes) {
                QuoteScreen()
            }
        }.ignoresSafeArea()
    }
    private func showQuotes() {
        self.shouldShowQuotes.toggle()
    }
}

struct QuoteScreen: View {
    @State private var quoteIndex = 0
    @State var currentQuote: Quote = dummyData[0]  // <--- here, do not use "quoteIndex"

    var body: some View {
        ZStack {
            Color.orange
            VStack {
                QuoteView(quote: $currentQuote) // <--- here
                Spacer()
                HStack {
                    Button(action: degress) {
                        Image(systemName: "arrow.left.square.fill")
                            .resizable()
                            .frame(width: 50, height: 50)
                    }
                    Spacer()
                    Button(action: progress) {
                        Image(systemName: "arrow.right.square.fill")
                            .resizable()
                            .frame(width: 50, height: 50)
                    }
                }
                .padding(28)
                //.buttonStyle(.plain) Safe to uncomment if Xcode 13

            }
        }.ignoresSafeArea()
    }
    // you will have to adjust this to your needs
        private func progress() {
    let prevValue = quoteIndex
    quoteIndex += 1
    if let thisQuote = dummyData.first(where: { $0.index == quoteIndex}) { // <--- here
        currentQuote = thisQuote
    } else {
        quoteIndex = prevValue
    }
}
// you will have to adjust this to your needs
private func degress() {
    let prevValue = quoteIndex
    quoteIndex -= 1
    if let thisQuote = dummyData.first(where: { $0.index == quoteIndex}) { // <--- here
        currentQuote = thisQuote
    } else {
        quoteIndex = prevValue
    }
}
}

struct QuoteView: View {
    @State private var showQuotes = false
    @Binding var quote: Quote // <--- here
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 25)
                .stroke(lineWidth: 2)
            VStack {
                Text(quote.quote)
                    .frame(maxWidth: 300) // <--- here missing leading "."
                Text(quote.author)
                    .frame(maxWidth: 300, alignment: .trailing)
                    .foregroundColor(.secondary)
            }

        }.navigationBarHidden(true)
            .frame(height: 400)
            .padding()
    }
}

struct Quote: Identifiable {
    let id = UUID()
    var quote: String
    var author: String
    var index: Int
}

A: This crash is not caused by the array access but by a typo in your code. You can see that if you run it in the simulator and look at the stack trace. It gets in an endless loop in the internals of SwiftUI. The reason is the missing dot before the frame modifier:

struct QuoteView: View {
    @State private var showQuotes = false
    let quote: Quote
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 25)
                .stroke(lineWidth: 2)
            VStack {
                Text(quote.quote)
                frame(maxWidth: 300)  << !!!!! missing dot
                Text(quote.author)
                    .frame(maxWidth: 300, alignment: .trailing)
                    .foregroundColor(.secondary)
            }

        }.navigationBarHidden(true)
        .frame(height: 400)
            .padding()
    }
}

This calls the frame method on the QuoteView and not on the Text - which is an invalid operation.


text:
Q: how often the Google Fit sync data between different devices and how they sync? Say I login the same google account on two devices, both are tracking my steps via Google Fit.
How often the Google fit sync the steps between these two devices?
If one device recorded 100 steps, while another recorded 200 at the same period,  they Google fit sync the data, how many steps will end up on both devices? 100 ? 200? or 300? How it works?


text:
Q: Change font size inside a frame with javascript? I have a html page

<frameset cols="*" rows="48,100%" border="0" frameborder="yes" bordercolor="black">
    <frame name="header" src="bar.jsp" scrolling="no" marginheight="0" marginwidth="0" frameborder="0">
    <frame name="body" src="body.jsp" scrolling="auto" marginheight="0" marginwidth="0" frameborder="0">
    <frame>
</frameset>

Inside frame body I have the page body.jsp:

How to change the font size for all rows inside table?

A: It looks like your frames are the same domain so thats good. What you can do is insert a CSS file onto your frames using javascript, and then target whatever you want.
Something similar to this question:
var cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
frames['body'].document.head.appendChild(cssLink);

and in that css file add something like:
#people tr{
   font-size:12pt;
}


text:
Q: ::SendMessage( ) LRESULT result = ::SendMessage(hWnd, s_MaxGetTaskInterface, (WPARAM)&pUnkReturn, 0);

The value of result after the call is 0
I expect it to return with a valid value of pUnkReturn , but it returns with a NULL value .
Necessary Information before this call  :
const UINT CMotionUtils::s_MaxGetTaskInterface =  RegisterWindowMessage(_T("NI:Max:GetTaskInterface"));

The value of s_MaxGetTaskInterface i get here is 49896 .
The value of hWnd is also proper .  I checked that with Spy++ ( Visual Studio tool ) .
Microft Spy++ Messages window shows me the following for this window .
<00001> 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]wParam:0224C2D0 lParam:00000000
<00002> 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]lResult:00000000

Please help me to get a valid address stored in pUnkReturn after the call .

A: I think the & in &pUnkReturn is needed, based on the hungarian prefix. I expect pUnkReturn to have type IUnknown*. The message receiver will provide the IUnknown*. The address where it will store that IUnknown* is an IUnknown**. Hence, this code passes in &pUnkReturn and the message receiver writes to *(IUnknown**)wParam.

A: Is the destination hWnd in the same process? If not, you won't be able to pass (or return) a pointer through the message. Note that Windows implements marshalling for built-in messages.

A: When I Googled for NI:Max:GetTaskInterface I couldn't find anything. In general, how a window will handle a given message depends entirely on the window concerned. Does the window (specified by hWnd) even support the NI:Max:GetTaskInterface message?

A: You're going to have to provide more information - what is "GetTaskInterface" (Google provides no results). SendMessage will return with whatever value is returned from the WndProc that handles the message "s_MaxGetTaskInterface". If it's not handled, you will get zero back and your pointer will still be NULL.

A: You'll need to tell us what pUnkReturn is and how it's defined.
You'll also need to tell us what the handler for s_MaxGetTaskInterface is expecting.
If you expect the handler to populate whatever is pointed to by pUnkReturn, then you'll need to call SendMessage with (WPARAM)pUnkReturn, however if the handler returns a pointer, then call as you're doing now.

A: The problem is not with how you are calling SendMessage().  The problem is in your implementation of the message handler for the "NI:Max:GetTaskInterface" registered message.
The value that SendMessage() returns is the same as the value that is returned from your message handler.  If you need pUnkReturn to be an out-val, then your message handler must populate it.
Let's see the code for your message handler.


text:
Q: How do I start a console application in one project from a web form in another project? I have a website created in VS 2010 with .NET 4.0.  There are multiple projects in the solution.  In one of the projects I have a form that gives a user the option to run a console application that is in another project of the solution. (called update.exe)
I have tried just using
process.start(filepath + "update.exe")
but it doesn't seem to run.
It finds the file but then finishes immediately.  I tried adding Console.readKey() to the console application so it would stay open after being called, but it was to no avail.
On top of this, I know that the console app isn't running as I have logs set up throughout the console's code and it never even seems to kick off.
Should I be calling the console app differently?  (note: I am writing in VB.net)
Thanks!

A: Purely speculative here.. but my guess is that when the page finishes processing the process is terminated.  Try having the page wait for the process to close.

A: My 'work-around' for a similar requirement is this:
Use the ASP page to create a CMD or BAT file on the server.
Create/write a service that 'watches' for the CMD/BAT file - and when it finds one, it runs it. The service can be written to start a process as a user.


text:
Q: Retrieve processing instructions using XDocument I have an XML document containing processing instructions. I know that, with the XmlDocument class, you can use
var node = xmlDoc.SelectSingleNode("processing-instruction('xml-stylesheet')") as XmlProcessingInstruction;

but I want to use XDocument. How can I do this?

A: This is how I access an XML file's nodes with the XDocument class.
However, you'll have to be more specific on what you want to do with it.
XDocument doc = XDocument.Load("filepath");
var node = doc.Nodes().OfType<XElement>().SingleOrDefault(n => n.Name == "node name");
var node_value = node.Value;
var node_descendants = node.Descendants();

UPDATE:
As you may have noticed there's no SelectSingleNode in XDocument, in fact, to retrieve the node you want you'll have to fetch it from the corresponding ienumerable collection, or alternatively from the predefined FirstNode, NextNode, PreviousNode, LastNode, but you cannot apply any filters to those. Therefore the only ways to retrieve ProcessingInstruction nodes are
var pI_nodes = doc.Nodes().OfType<XProcessingInstruction>();

And
var pI_nodes = (from node in doc.Nodes()
                where node.NodeType == System.Xml.XmlNodeType.ProcessingInstruction
                select node);

If you expect to retrieve several ProcessingInstructions and need to filter these as well, the equivalent to the node name would the Target property
var filtered_pIs = pI_nodes_1.Where(pI => pI.Target == "xml-stylesheet");

And as a final reminder the value of the processing instruction is stored in the Data property.
string pI_value = filtered_pIs.First().Data

A: Here is one way:
var node = xDoc.Root.Nodes().OfType<XProcessingInstruction>().First();


text:
Q: Send Bootstrap Tab's ID to View.py via Django I am trying to send tabs id to the the server from Django template. I want to send the selected tab's ID after submit the page. Is there any way to do that? Or How can I put my id into my url? Thank you in advance.
Here is my tab list:

MyFirstTab

MySeconfTab

A: You could use Javascript (jQuery) to append the current tab ID to the form before it is submitted to the server.  Something like this:
$(function() {
    $( "#form" ).submit(function( event ) {
        var currentTabID = $("ul#myTab li.active a").attr('id');
        $('<input>').attr({
            type: 'hidden',
            name: 'currentTabID',
            value: currentTabID
        }).appendTo(this);
    });
});

Then, in your Django view, you can access that data via request.POST.get("currentTabID")


text:
Q: Error knitting Rmarkdown doc: Error in bzfile(filename, "rb") : cannot open the connection So I am trying to knit my code for an assignment on Coursera but I am encountering a strange error and I cant figure out the issue. Here is the code that I believe is the problem
setInternet2(use = TRUE)

fileUrl<- "https://d396qusza40orc.cloudfront.net/repdata%2Fdata%2FStormData.csv.bz2"

download.file(fileUrl, destfile = "c:/Users/musto101/Dropbox/DataScience/ReproducibleResearch/Assignment2/data/stormData.csv.bz2")

dateDownloaded<- date()

library(R.utils)

stormData<-bunzip2( filename = "stormData.csv", destname = "stormData3.csv")

head(stormData)

and the error:
Quitting from lines 13-35 (PA2.Rmd)
Error in bzfile(filename, "rb") : cannot open the connection
Calls: <Anonymous> ... eval -> eval -> bunzip2 -> bunzip2.default -> bzfile
In addition: Warning messages:
1: package 'R.utils' was built under R version 3.1.1
2: package 'R.oo' was built under R version 3.1.1
3: package 'R.methodsS3' was built under R version 3.1.1
4: In bzfile(filename, "rb") :
  cannot open bzip2-ed file 'stormData.csv', probable reason 'No such file or directory'
Execution halted

So does anyone have a clue what is going on here? Any advice would be gratefully received.
Thanks

A: Looks like you forgot the .BZ2 suffix on the input filename.  Code below should fix this.
stormData<-bunzip2( filename = "stormData.csv.bz2", destname = "stormData3.csv")

A: Just put a
require(R.utils)

at the top of that chunk and it will work fine. I had the same issue. I have this with a few other packages like dplyr too. Same resolution or put in R.utils:::bunzip2()


text:
Q: Count no of lines between two lines How to achieve the following. Here is a sample text file..
AH
1
2
3
BH
21
BT03
CH
CT02
AT10

This is a sample text file. I need read each line and find the count.. For example, there are 10 Lines within A record.. And 3 lines within B record and two lines within C Record.
How do I get this count. H-Header and T-Trailer.  You may say,  read the T record to find the count, but that count might be wrong.  Hence I am trying to find the count and update the trailer records correctly.
I cannot upload the Java code I have written as I'm on mobile now.. Any suggestions is highly appreciated
Thanks

A: I'm not sure if I understand your question, you just want to count lines in a file? Try something like this:
Path path = Paths.get("yourFile.txt");
long lineCount = Files.lines(path).count();

A: use below code and read all file in array.
String[] stringArray = new String[10];

    int length = stringArray.length;
    for (int i = 0; i < length; i++) {
        String stringI = stringArray[i];
        if (stringI.contains("H")) {
            // Head rec
            String headRecName = stringI.replace("H", "");
            int count = 1;
            for (int j = i + 1; j < length; j++) {
                count++;
                String stringJ = stringArray[j];
                if (stringJ.contains("T") && headRecName.equals(stringJ.replace("T", ""))) {
                    stringArray[j] = stringArray[j] + count;
                }

            }

        }

    }

}


text:
Q: Redirect loop with Grails Spring Security CAS plugin I am working with a project involving CAS server works with other Spring-based projects using Single-Sign On (SSO), but I am receiving a redirect loop involving the Grails spring-security-cas plugin (version: ":spring-security-cas:2.0-RC1"). I've looked at the plugin's documentation. I know CAS redirect questions appear common, but I have yet to find a posting related to this type of situation. I am new-ish to the Grails and CAS worlds, so thank you in advance for any push in the right direction.
Accessing a secured page on the grails app initially redirects to the CAS server login page correctly, with the appropriate service parameter: https:// example.com:8443/cas/login?service=http:// example.com:8080/grailsapp/j_spring_cas_security_check
The problem occurs after the user logs in successfully and CAS redirects back to the service. The j_spring_cas_security_check in the grails app is redirecting back to the https://example.com:8443/cas login page, which sees the TGC and redirects back to the service j_spring_cas_security_check page, which redirects ad infinitum [until the browser gives the redirect loop error]. It also looks like new service tickets are getting created each iteration.
My Config.groovy has:
grails.plugin.springsecurity.cas.loginUri = /login
grails.plugin.springsecurity.cas.serviceUrl = http://example.com:8080/grailsapp/j_spring_cas_security_check
grails.plugin.springsecurity.cas.serverUrlPrefix = https://example.com:8443/cas
# we aren't using cas with proxy
# logout details not shown here

Unsuccessful attempts already tried based on other questions/answers:

*

*I don't think the issue is with the cas server: when I go directly to another of the projects already using CAS they detect the ticket cookie and login just fine without the user having to authenticate again.

*The SSL certificate is self-signed and already added to Java's cacert store. No SSLHandshake or Certificate-related exceptions, etc. occur.

*It's not a bad credentials or proxy situation like question 19710841, but I've tried adding the /j_spring_cas_security_check to the Annotation staticRules anyways but get the same loop.

The cas server's logs include:
=============================================================
WHO: [username: sampleuser]
WHAT: supplied credentials: [username: sampleuser]
ACTION: AUTHENTICATION_SUCCESS
APPLICATION: CAS
WHEN: Fri Jan 03 23:52:41 GMT 2014
CLIENT IP ADDRESS: XXX.XXX.XXX.XXX
SERVER IP ADDRESS: example.com
=============================================================
=============================================================
WHO: [username: sampleuser]
WHAT: TGT-24-Rttmt5i5raWcV1Z5wZavVopigQc4xeIckEUfMKdG3EwEzI3LUI-cas.service
ACTION: TICKET_GRANTING_TICKET_CREATED
APPLICATION: CAS
WHEN: Fri Jan 03 23:52:41 GMT 2014
CLIENT IP ADDRESS: XXX.XXX.XXX.XXX
SERVER IP ADDRESS: example.com
=============================================================

INFO [org.jasig.cas.CentralAuthenticationServiceImpl] - <Granted service ticket [ST-77-cneJOIwmnoOdKqkscaiy-cas.service] for service [http://example.com:8080/grailsapp/j_spring_cas_security_check] for user [sampleuser]>

####### FIRST ITERATION OF LOOP BELOW #############

=============================================================
WHO: sampleuser
WHAT: ST-77-cneJOIwmnoOdKqkscaiy-cas.service for http://example.com:8080/grailsapp/j_spring_cas_security_check
ACTION: SERVICE_TICKET_CREATED
APPLICATION: CAS
WHEN: Fri Jan 03 23:52:41 GMT 2014
CLIENT IP ADDRESS: XXX.XXX.XXX.XXX
SERVER IP ADDRESS: example.com
=============================================================
=============================================================
WHO: audit:unknown
WHAT: ST-77-cneJOIwmnoOdKqkscaiy-cas.service
ACTION: SERVICE_TICKET_VALIDATED
APPLICATION: CAS
WHEN: Fri Jan 03 23:52:41 GMT 2014
CLIENT IP ADDRESS: 127.0.0.1
SERVER IP ADDRESS: example.com
=============================================================

DEBUG [org.jasig.cas.web.flow.InitialFlowSetupAction] - <Placing service in FlowScope: http://example.com:8080/grailsapp/j_spring_cas_security_check>
INFO [org.jasig.cas.CentralAuthenticationServiceImpl] - <Granted service ticket [ST-78-6qsbaVNNOess4VhGOQE4-cas.service] for service [http://example.com:8080/grailsapp/j_spring_cas_security_check] for user [sampleuser]>

####### SERVICE_TICKET_CREATED and SERVICE_TICKET_VALIDATED LOOP CONTINUES A FEW MORE TIMES BEFORE BROWSER GIVES UP #############

A: The issue was that in the Grails client I did not create a userDetailsService. I implemented a custom class within Grails' services folder (See http://grails-plugins.github.io/grails-spring-security-core/guide/userDetailsService.html):
public class MyUserDetailsService implements UserDetailsService {
    // Required methods here
}

then referenced this in resources.groovy:
beans = {
    userDetailsService(MyUserDetailsService)
}

A: In addition to overwriting UserDetailsService I had to configure filterProcessesUrl in Config.groovy
grails.plugin.springsecurity.cas.filterProcessesUrl = "/user/login" // same as uri part of serviceUrl
grails.plugin.springsecurity.cas.serviceUrl = "http://yoursite.com/user/login"

for CasAuthenticationFilter to kick in after authentication on CAS. Following are source code reference links:
You can also look at the source for CasAuthenticationFilter.java
 see the serviceTicketRequest and super.requiresAuthentication methods.